如何使用自定义的参考与JSON.NET解决 [英] How to use custom reference resolving with JSON.NET
问题描述
我有以下的JSON:
{
"id" : "2"
"categoryId" : "35"
"type" : "item"
"name" : "hamburger"
}
{
"id" : "35"
"type" : "category"
"name" : "drinks"
}
和我想它匹配这个对象:
And I want to match it to this object:
public class Item
{
[JsonProperty(PropertyName = "categoryId")]
public Category Category { get; set; }
}
类别
是键入实体
具有字符串
编号
属性,我可以的访问。我想通过JSON解串器创建了35的对象映射到类别
在属性Item
。
Category
is of type Entity
which has a string
Id
property I can access. I want the "35" object created by the JSON Deserializer to be mapped to the Category
property in the Item
.
据的文档,我应使用 IReferenceResolver
。我将如何实现这个接口,并将其挂接到JSON.NET框架?
According to the documentation, I should use a IReferenceResolver
. How would I implement this interface and hook it into the JSON.NET framework?
推荐答案
您可以在JsonSerializerSettings指定自定义IRefenceResover
You can specify a custom IRefenceResover in your JsonSerializerSettings:
JsonSerializerSettings settings = new JsonSerializerSettings ();
settings.ReferenceResolver = new IDReferenceResolver ();
有是的 IDReferenceResolver 对于具有的的Guid 的 ID对象属性。该引用字符串现在是对象的标识,除了你所使用的是类似于您的使用情况的 INT 的而不是的Guid 的类型你的身份证。酒店
There is an excellent implementation example of IDReferenceResolver for objects with a Guid id property. The reference string is now the object's id, which is similar to your use case except that your are using int instead of Guid types for your 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;
}
}
}
这篇关于如何使用自定义的参考与JSON.NET解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!