2011-08-09 20 views
15

में संपत्ति-आधारित प्रकार का संकल्प JSON ऑब्जेक्ट की संपत्ति के आधार पर JSON.NET का उपयोग करके प्रकार समाधान को ओवरराइड करना संभव है? मौजूदा एपीआई के आधार पर, ऐसा लगता है कि मुझे JsonPropertyCollection स्वीकार करने और Type को वापस करने के लिए एक तरीका चाहिए।JSON.NET

नोट: मुझे TypeNameHandling attribute पता है, लेकिन यह $type संपत्ति जोड़ता है। मेरे पास स्रोत JSON पर नियंत्रण नहीं है।

उत्तर

14

ऐसा प्रतीत होता है कि इसे एक कस्टम JsonConverter बनाकर संभाला जाता है और इसे deserialisation से पहले JsonSerializerSettings.Converters में जोड़ दिया जाता है।

nonplus ने कोडप्लेक्स पर JSON.NET discussions board पर एक आसान नमूना छोड़ा है। मैंने स्पॉट पर ऑब्जेक्ट इंस्टेंस बनाने के बजाय कस्टम Type को वापस करने और डिफ़ॉल्ट निर्माण तंत्र का संदर्भ देने के लिए नमूना संशोधित किया है।

class VehicleConverter : JsonCreationConverter<Vehicle> 
{ 
    protected override Type GetType(Type objectType, JObject jObject) 
    { 
     var type = (string)jObject.Property("Type"); 
     switch (type) 
     { 
      case "Car": 
       return typeof(Car); 
      case "Bike": 
       return typeof(Bike); 
     } 

     throw new ApplicationException(String.Format(
      "The given vehicle type {0} is not supported!", type)); 
    } 
} 
+0

क्या लागू नहीं किया गया सार 'WriteJson' विधि के बारे में:

abstract class JsonCreationConverter<T> : JsonConverter { /// <summary> /// Create an instance of objectType, based properties in the JSON object /// </summary> protected abstract Type GetType(Type objectType, JObject jObject); public override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jObject = JObject.Load(reader); Type targetType = GetType(objectType, jObject); // TODO: Change this to the Json.Net-built-in way of creating instances object target = Activator.CreateInstance(targetType); serializer.Populate(jObject.CreateReader(), target); return target; } } 

और यहाँ उदाहरण उपयोग (यह भी जैसा कि ऊपर उल्लेख अद्यतन) है? –

+1

@ CanPoyrazoğlu आप CanWrite संपत्ति को ओवरराइड करना चाहते हैं और इसे गलत पर सेट करना चाहते हैं। यह कनवर्टर अपने डिफ़ॉल्ट व्यवहार में वापस आ जाएगा। – bmeredith