2016-06-07 90 views
0

我有这样一个对象,以便:添加JSON.NET解析错误到JsonExtensionData

public class Foo 
{ 
    int bar; 
    [JsonExtensionData] public Dictionary<string, object> Catchall; 
} 

和JSON像这样: jsonString = { "bar": "not an int", "dink": 1 }

所以,如果我var foo = JsonConvert.DeserializeObject<Foo>(jsonString)

bar将无法​​进入反序列化类Foo,因为它是错误的类型,但可以将它插入到[JsonExtensionData] Catchall字典中吗?

+0

如果你这样做,以后如果你重新序列化你的'Foo'类,你最终会在JSON中产生重复的''bar''属性,这可能是有问题的。请参阅[JSON.Net重复属性在派生对象的基础包含字典属性的序列化](https://stackoverflow.com/questions/33434251/json-net-duplicate-properties-on-serialization-of-derived-object -where基-CONT)。 – dbc

回答

0

您可以[JsonIgnore]标记属性bar,然后手动将Catchall字典中适当serialization callbacks添加和删除其值:

public class Foo 
{ 
    const string barName = "bar"; 

    [JsonIgnore] 
    public int? Bar { get; set; } 

    [JsonExtensionData] 
    public Dictionary<string, object> Catchall; 

    [OnSerializing] 
    void OnSerializing(StreamingContext ctx) 
    { 
     if (Catchall == null) 
      Catchall = new Dictionary<string, object>(); 
     if (Bar != null) 
      Catchall[barName] = Bar.Value; 
    } 

    [OnSerialized] 
    void OnSerialized(StreamingContext ctx) 
    { 
     if (Catchall != null) 
      Catchall.Remove(barName); 
    } 

    [OnDeserialized] 
    void OnDeserializedMethod(StreamingContext context) 
    { 
     if (Catchall != null) 
     { 
      object value; 
      if (Catchall.TryGetValue(barName, out value)) 
      { 
       try 
       { 
        if (value == null) 
        { 
         Bar = null; 
        } 
        else 
        { 
         Bar = (int)JToken.FromObject(value); 
        } 
        Catchall.Remove(barName); 
       } 
       catch (Exception) 
       { 
        Debug.WriteLine(string.Format("Value \"{0}\" of {1} was not an integer", value, barName)); 
       } 
      } 
     } 
    } 
} 

请注意,我已经改变bar是一个public int? Bar { get; set; }。空值表示Bar的整数值未反序列化,因此,在重新序列化时,字典中的值(如果有)不应被属性的值所取代。