使用JSON.NET将已知和未知的JSON字段反序列化为CLR对象

时间:2014-06-12 09:15:49

标签: c# .net json json.net

我有以下JSON有效负载:

{
    "id": 1,
    "foo": "bar",
    "bar": "foo",
    "attr_1": ["foo", "bar"],
    "attr_2": ["foo2", "bar2"]
}

我还有以下CLR对象:

public class Obj
{
    public int Id { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }

    [JsonExtensionData]
    public IDictionary<string, string[]> Properties { get; set; }
}

如果我尝试对其进行反序列化,则会失败:

using (FileStream file = File.Open(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "file.txt"), FileMode.Open))
using (StreamReader reader = new StreamReader(file))
{
    Obj foo = JsonConvert.DeserializeObject<Obj>(reader.ReadToEnd());
}

There is already an answer to a similar question。但是,逐个读取和写入每个字段并不是一个解决方案。将剩余字段反序列化为IDictionary<string, string[]>的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

Json.NET源代码中的

This line强制将值类型设置为JToken。我认为最简单的方法是为序列化创建另一种类型。

public class SerializationModel
{
    public int Id { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }

    [JsonExtensionData]
    public IDictionary<string, JToken> Properties { get; set; }
}

class Model
{
    public int Id { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
    public Dictionary<string, string[]> Properties { get; set; }
}

[Test]
public void DeserializeTest()
{
    string data = File.ReadAllText("data.txt");
    SerializationModel serializationModel = JsonConvert.DeserializeObject<SerializationModel>(data);

    Model model = new Model
    {
        Id = serializationModel.Id,
        Foo = serializationModel.Foo,
        Bar = serializationModel.Bar,
        Properties = serializationModel.Properties.ToDictionary(item => item.Key, pair => pair.Value.ToObject<string[]>())
    };

}