Deserialize array of key value pairs using Json.NET

前端 未结 4 1272
南笙
南笙 2020-12-03 13:51

Given the following json:

[ {\"id\":\"123\", ... \"data\":[{\"key1\":\"val1\"}, {\"key2\":\"val2\"}], ...}, ... ]

that is part of a bigger

4条回答
  •  有刺的猬
    2020-12-03 14:26

    The simplest way is deserialize array of key-value pairs to IDictionary:

    
    public class SomeData
    {
        public string Id { get; set; }
    
        public IEnumerable> Data { get; set; }
    }
    
    private static void Main(string[] args)
    {
        var json = "{ \"id\": \"123\", \"data\": [ { \"key1\": \"val1\" }, { \"key2\" : \"val2\" } ] }";
    
        var obj = JsonConvert.DeserializeObject(json);
    }
    
    

    But if you need deserialize that to your own class, it can be looks like that:

    
    public class SomeData2
    {
        public string Id { get; set; }
    
        public List Data { get; set; }
    }
    
    public class SomeDataPair
    {
        public string Key { get; set; }
    
        public string Value { get; set; }
    }
    
    private static void Main(string[] args)
    {
        var json = "{ \"id\": \"123\", \"data\": [ { \"key1\": \"val1\" }, { \"key2\" : \"val2\" } ] }";
    
        var rawObj = JObject.Parse(json);
    
        var obj2 = new SomeData2
        {
            Id = (string)rawObj["id"],
            Data = new List()
        };
    
        foreach (var item in rawObj["data"])
        {
            foreach (var prop in item)
            {
                var property = prop as JProperty;
    
                if (property != null)
                {
                    obj2.Data.Add(new SomeDataPair() { Key = property.Name, Value = property.Value.ToString() });
                }
    
            }
        }
    }
    
    

    See that I khow that Value is string and i call ToString() method, there can be another complex class.

提交回复
热议问题