反序列化包含数组的JSON数据

时间:2015-10-30 18:22:15

标签: c# serialization json.net

我想反序列化有三个键的JSON数据,如下所示:Type,Name,Data []

我希望将JSON序列化为我的Message类:

class Message
{
    public int Type;
    public string Name;
    public List<KeyValuePair<string, string>> Data;
}

我可以使用这段代码反序列化Type和Name;

Message DeserializedMessage = JsonConvert.DeserializeObject<Message>(myString);
Console.WriteLine("Name: " + DeserializedMessage.Name);
Console.WriteLine("Type: " + DeserializedMessage.Type); 

但是,我不知道如何将JSON中的键值对反序列化为List<KeyValuePair<string, string>> Data;

示例JSON:

{
    "Type":"103",
    "Name":"Oguzhan",
    "Data":
    [
        {
            "InviteTo":"Bahadir"
        }
    ]
}

{
    "Type":"104",
    "Name":"Oguzhan",
    "Data":
    [
        {
            "Game":"Backgammon",
            "Duration":"2"
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

你应该改变你的

public List<KeyValuePair<string, string>> data; 

public List<Dictionary<string, string>> data;

之后,它相对容易:

Message message = JsonConvert.DeserializeObject<Message>(jsonString);

或者,如果您想使用dynamic

dynamic parsed = JsonConvert.DeserializeObject(jsonString);
Message message = MapToMessage(parsed);

// ...

private Message MapToMessage(dynamic json)
{
    return new Message()
    {
        Type = json.Type,
        Name = json.Name,
        Data = ((IEnumerable<dynamic>)json.Data).Select(d =>
        {
            var dic = new Dictionary<string, string>();
            foreach (var v in d) dic.Add(v.Name, v.Value.Value);
            return dic;
         }).ToList()
    };
}