我有以下 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/