1

I have the same problem as this question in that I want to deserialize dynamic json data. In other words, the keys: "error1, etc are dynamic. In my case:

{
    "errors" : {
        "error1" : {
            "name"  : "connection error",
            "location" : "CPU board",
            "id"    : "E0001"
        },
        "warning2" : {
            "name"  : "Value not formatted",
            "location" : "Controller",
            "id"    : "W005"
        },
        "info4" : {
            "name"  : "Attention to temperature",
            "location" : "Heater",
            "id"    : "I008"
        }
    }
}

In the question, the answer uses JsonConvert to deserialize into a dictionary. I have found also here that something similar can be done using JavascriptSerializer.

I suppose that I can use those to solve my problem but my question is, can I do this too using DataContractJsonSerializer?

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150

3 Answers3

0

You can deserialize it simple as dictionary of objects:

var result = JsonConvert.DeserializeObject<Error>(json);

Implement a class like the following:

public class Error
{
  public class Details
  {
    public string Name {get;set}
    public string Id {get;set}
    public string Location {get;set}
  }
  public Dictionary<string, Details> Errors {get;set;}
}
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
  • Yes, thanks. How about doing it using DataContractJsonSerializer? – KansaiRobot Feb 08 '19 at 08:42
  • You need to use DataContract and DataMember attributes in your class: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-serialize-and-deserialize-json-data – Piotr Stapp Feb 08 '19 at 08:51
  • I mean how to do the above with DataContractJsonSerializer (I know DataContract is required) – KansaiRobot Feb 08 '19 at 08:56
0

You can do the following:

using(MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
    Error deserializedError = new Error();
    DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedError.GetType());

    deserializedError = ser.ReadObject(ms) as Error;  
}
Tony Abrams
  • 4,505
  • 3
  • 25
  • 32
0

If you want to access the object data like errors.error1.name etc.. then consider using dynamic and ExpandoObject. Here is a working example

using (var f = new StreamReader("json1.json"))
{
    string json = f.ReadToEnd();
    dynamic deserializedObject = JsonConvert.DeserializeObject<ExpandoObject>(json);

    Console.WriteLine(deserializesObject.errors.error1.name);
}

Output: connection error

I hope this helps.

darcane
  • 473
  • 3
  • 14