c# - 如何使用 JSON.NET 的自定义引用解析

标签 c# json json.net

我有以下 JSON:

{
           "id" : "2"
   "categoryId" : "35"
         "type" : "item"
         "name" : "hamburger"
}
{
           "id" : "35"
         "type" : "category"
         "name" : "drinks" 
}

我想将它与这个对象匹配:

public class Item 
{
  [JsonProperty(PropertyName = "categoryId")]
  public Category Category { get; set; }
} 

Category 属于 Entity 类型,它具有我可以访问的 string Id 属性。我希望将 JSON Deserializer 创建的“35”对象映射到 Item 中的 Category 属性。

根据to the documentation ,我应该使用 IReferenceResolver。我将如何实现此接口(interface)并将其挂接到 JSON.NET 框架中?

最佳答案

您可以在 JsonSerializerSettings 中指定自定义 IRefenceResover:

JsonSerializerSettings settings = new JsonSerializerSettings ();
settings.ReferenceResolver = new IDReferenceResolver ();

IDReferenceResolver 有一个很好的实现示例对于具有 Guid id 属性的对象。引用字符串现在是对象的 id,这与您的用例类似,只是您使用的是 int 而不是 Guid 类型作为您的 id属性(property)。

using System;
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;

   namespace Newtonsoft.Json.Tests.TestObjects
   {
    public class IdReferenceResolver : IReferenceResolver
    {
        private readonly IDictionary<Guid, PersonReference> _people = new Dictionary<Guid, PersonReference>();

        public object ResolveReference(object context, string reference)
        {
            Guid id = new Guid(reference);

            PersonReference p;
            _people.TryGetValue(id, out p);

            return p;
        }

        public string GetReference(object context, object value)
        {
            PersonReference p = (PersonReference)value;
            _people[p.Id] = p;

            return p.Id.ToString();
        }

        public bool IsReferenced(object context, object value)
        {
            PersonReference p = (PersonReference)value;

            return _people.ContainsKey(p.Id);
        }

        public void AddReference(object context, string reference, object value)
        {
            Guid id = new Guid(reference);

            _people[id] = (PersonReference)value;
        }
    }
}

关于c# - 如何使用 JSON.NET 的自定义引用解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9237939/

相关文章:

c# - Angular 6 中的 cors 策略已阻止从源访问 xmlhttprequest

c# - 使用 Xamarin 从 iPhone 中的麦克风流式传输音频

json - Nginx返回带有伪造的200状态代码的空json对象

java - 将密码查询结果 (JSON) 解析为 Java 对象

c# - 我应该如何解析 JSON,它的键和值的重音被转义而不影响字段值中的转义?

c# - .NET 1.1 中未处理的异常处理程序

c# - C# 中具有多个 View (或分层 View )的模型 View 演示器

c# - 返回 json 的 <T> 字符串

c# - json.net 处理不存在的 token

c# - 提高 XmlSerializer 的性能