Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctly

前端 未结 5 1512
耶瑟儿~
耶瑟儿~ 2020-11-22 16:19

I have this JSON:

[
    {
        \"Attributes\": [
            {
                \"Key\": \"Name\",
                \"Value\": {
                    \"Value         


        
相关标签:
5条回答
  • 2020-11-22 17:08

    Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :

    var objResponse1 = 
        JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
    
    0 讨论(0)
  • 2020-11-22 17:09

    If one wants to support Generics (in an extension method) this is the pattern...

    public  static List<T> Deserialize<T>(this string SerializedJSONString)
    {
        var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
        return stuff;
    }
    

    It is used like this:

    var rc = new MyHttpClient(URL);
    //This response is the JSON Array (see posts above)
    var response = rc.SendRequest();
    var data = response.Deserialize<MyClassType>();
    

    MyClassType looks like this (must match name value pairs of JSON array)

    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
     public class MyClassType
     {
        [JsonProperty(PropertyName = "Id")]
        public string Id { get; set; }
    
        [JsonProperty(PropertyName = "Name")]
        public string Name { get; set; }
    
        [JsonProperty(PropertyName = "Description")]
        public string Description { get; set; }
    
        [JsonProperty(PropertyName = "Manager")]
        public string Manager { get; set; }
    
        [JsonProperty(PropertyName = "LastUpdate")]
        public DateTime LastUpdate { get; set; }
     }
    

    Use NUGET to download Newtonsoft.Json add a reference where needed...

    using Newtonsoft.Json;
    
    0 讨论(0)
  • 2020-11-22 17:09

    Use this, FrontData is JSON string:

    var objResponse1 = JsonConvert.DeserializeObject<List<DataTransfer>>(FrontData);  
    

    and extract list:

    var a = objResponse1[0];
    var b = a.CustomerData;
    
    0 讨论(0)
  • 2020-11-22 17:16
    var objResponse1 = 
    JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
    

    worked!

    0 讨论(0)
  • 2020-11-22 17:22

    Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:

    var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
    return des.data.Count.ToString();
    

    Deserializing JSON array into strongly typed .NET object

    0 讨论(0)
提交回复
热议问题