Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON with dynamic objects

Tags:

json

c#

restsharp

I have a JSON object that comes with a long list of area codes. Unfortunately each area code is the object name on a list in the Data object. How do I create a class that will allow RestSharp to deserialize the content?

Here's how my class looks now:

public class phaxioResponse
{
    public string success { get; set; }
    public string message { get; set; }
    public List<areaCode> data { get; set; }

    public class areaCode
    {
        public string city { get; set; }
        public string state { get; set; }
    }
}

And here's the JSON content:

{
    success: true
    message: "277 area codes available."
    data: {
        201: {
            city: "Bayonne, Jersey City, Union City"
            state: "New Jersey"
        }
        202: {
            city: "Washington"
        state: "District Of Columbia"
        } [...]
}
like image 733
Peter Schrøder Avatar asked May 06 '14 21:05

Peter Schrøder


People also ask

How do I deserialize JSON to an object?

NET objects (deserialize) A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

Can JSON be dynamic?

In simple terms, any valid JSON literal string is also a valid ObjectScript expression that evaluates to a dynamic entity.

What does Jsonconvert DeserializeObject do?

DeserializeObject Method. Deserializes the JSON to a . NET object.


2 Answers

I don't know anything about RestSharp, but if you're using Newtonsoft on the server side, then you can just pass a JObject to your method. Then you can interrogate the object to see what type of object it really is and use JObject.ToObject() to convert it.

like image 105
Ash8087 Avatar answered Sep 24 '22 06:09

Ash8087


Since this JSON is not C# friendly, I had to do a little bit of hackery to make it come out properly. However, the result is quite nice.

var json = JsonConvert.DeserializeObject<dynamic>(sampleJson);
var data = ((JObject)json.data).Children();
var stuff = data.Select(x => new { AreaCode = x.Path.Split('.')[1], City = x.First()["city"], State = x.Last()["state"] });

This code will generate an anonymous type that best represents the data. However, the anonymous type could be easily replaced by a ctor for a more normal DTO class.

The output looks something like this:

Deserialization Output

like image 39
Pete Garafano Avatar answered Sep 24 '22 06:09

Pete Garafano