Jmocke Jmocke - 3 months ago 10
JSON Question

Generic Pattern: Cannot deserialize the JSON array

I am trying to write a generic pattern to deserialize my json array string.
i have the following object created bellow:

public interface IDataResponse<T> where T: class
{
List<T> Data { get; set; }
}

public class DataResponse<T>: IDataResponse<T> where T: class
{
[JsonProperty("value")]
public List<T> Data { get; set; }
}


My json format

{
"values":{
"value":[
{
"value_1":"aaaaaa",
"value_2":"aaaaaa",
"value_3":"aaaaaa"
},
{
"value_1":"bbbbbb",
"value_2":"bbbbbb",
"value_3":"bbbbbb"
}
]
}
}


Now i can use this pattern like that

var myData = JsonConvert.DeserializeObject<List<DataResponse<MyData>>>(result);


where result is the json array string.

But ruuning this code , i got the exception bellow


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


How cani fix this error?

Answer

I'm not sure to well understand but, Haven't you missed the parent container of your list ?

I share you a code to desrialize your data

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string result = @"
{  
   'values':{  
   'value':[
     {  
        'value_1':'aaaaaa',
        'value_2':'aaaaaa',
        'value_3':'aaaaaa'
     },
     {  
        'value_1':'bbbbbb',
        'value_2':'bbbbbb',
        'value_3':'bbbbbb'
     }
  ]
  }
}";

            var myData = JsonConvert.DeserializeObject<MyContent<MyData>>(result);
        }
    }

    public class MyContent<T> where T : class
    {

        [JsonProperty("values")]
        public DataResponse<T> Values { get; set; }
    }

    [Serializable]
    public class MyData
    {
        public string value_1 { get; set; }
        public string value_2 { get; set; }
        public string value_3 { get; set; }
    }

    public interface IDataResponse<T> where T : class
    {
        List<T> Data { get; set; }
    }

    public class DataResponse<T> : IDataResponse<T> where T : class
    {
        [JsonProperty("value")]
        public List<T> Data { get; set; }
    }
}
Comments