Deserializing JSON array into strongly typed .NET object

前端 未结 8 759
一个人的身影
一个人的身影 2020-11-30 07:35

When I can call the 3rd party api and get back a single class worth of data everything deserialises fine using this code

TheUser me = jsonSerializer.Deseria         


        
8条回答
  •  心在旅途
    2020-11-30 07:44

    Afer looking at the source, for WP7 Hammock doesn't actually use Json.Net for JSON parsing. Instead it uses it's own parser which doesn't cope with custom types very well.

    If using Json.Net directly it is possible to deserialize to a strongly typed collection inside a wrapper object.

    var response = @"
        {
            ""data"": [
                {
                    ""name"": ""A Jones"",
                    ""id"": ""500015763""
                },
                {
                    ""name"": ""B Smith"",
                    ""id"": ""504986213""
                },
                {
                    ""name"": ""C Brown"",
                    ""id"": ""509034361""
                }
            ]
        }
    ";
    
    var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass));
    
    return des.data.Count.ToString();
    

    and with:

    public class MyClass
    {
        public List data { get; set; }
    }
    
    public class User
    {
        public string name { get; set; }
        public string id { get; set; }
    }
    

    Having to create the extra object with the data property is annoying but that's a consequence of the way the JSON formatted object is constructed.

    Documentation: Serializing and Deserializing JSON

提交回复
热议问题