Search code examples
c#.netjsonjson.netdatacontractserializer

Trying to deserialize JSON using JSON.NET and DataContractJsonSerializer fails


plz help, I'm stuck. I have a WCF service which returns something like this:

{
   "GetDataRESTResult":
     [
       {"Key1":100.0000,"Key2":1,"Key3":"Min"},
       {"Key1":100.0000,"Key2":2,"Key3":"Max"}
     ]
}

and I would like to deserialize it, but whatever I use (JSON.NET or DataContractJsonSerializer) I'm getting errors. When using DataContractJsonSerializer I'm using theis code:

byte[] data = Encoding.UTF8.GetBytes(e.Result);
MemoryStream memStream = new MemoryStream(data);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<DataDC>));
List<DataDC> pricinglist = (List<DataDC>)serializer.ReadObject(memStream);

where DataDC is the data contract which I've got from the service reference of the WCF REST service I'm getting the JSON data from, and the error I'm getting is InvalidCastException...

Trying to use JSON.NET I get another exception, but still nothing I can figure out, can anyone help please?

EDIT Here's a JSON.NET stacktrace:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyApp.MyServiceReference.DataDC]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'GetDataRESTResult', line 1, position 23.


Solution

  • Below code works

    string json = @" {""GetDataRESTResult"":[{""Key1"":100.0000,""Key2"":1,""Key3"":""Min""},{""Key1"":100.0000,""Key2"":2,""Key3"":""Max""}]}";
    
    dynamic dynObj = JsonConvert.DeserializeObject(json);
    foreach (var item in dynObj.GetDataRESTResult)
    {
        Console.WriteLine("{0} {1} {2}", item.Key1, item.Key3, item.Key3);
    }
    

    You can also use Linq

    var jObj = (JObject)JsonConvert.DeserializeObject(json);
    var result = jObj["GetDataRESTResult"]
                    .Select(item => new
                    {
                        Key1 = (double)item["Key1"],
                        Key2 = (int)item["Key2"],
                        Key3 = (string)item["Key3"],
                    })
                    .ToList();