将JSON.NET解析错误添加到JsonExtensionData中

时间:2016-06-07 23:00:31

标签: c# json json.net

我有一个像这样的对象:

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字典中?

1 个答案:

答案 0 :(得分:0)

您可以使用[JsonIgnore]标记属性bar,然后在相应serialization callbacksCatchall字典中手动添加和删除其值:

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; }。 null值表示Bar的整数值未反序列化,因此,重新序列化时,字典中的值(如果有)不应被属性值取代。