How to use custom reference resolving with JSON.NET

前端 未结 2 1593
攒了一身酷
攒了一身酷 2020-12-29 11:21

I have the following JSON:

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


        
2条回答
  •  一生所求
    2020-12-29 11:39

    You can specify a custom IRefenceResover in your JsonSerializerSettings:

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

    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 _people = new Dictionary();
    
            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;
            }
        }
    }
    

提交回复
热议问题