Deserialize JSON with dynamic objects

浪尽此生 提交于 2019-11-27 06:43:20

问题


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"
        } [...]
}

回答1:


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:




回答2:


your json is incorrect, but if you do correct it you can use a json-to-csharp tool like the one on http://json2csharp.com/ to generate your classes:

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

public class Data
{
    public __invalid_type__201 __invalid_name__201 { get; set; }
}

public class RootObject
{
    public bool success { get; set; }
    public string message { get; set; }
    public Data data { get; set; }
}



回答3:


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.




回答4:


I think using Dictionary<int,areaCode> is the easiest way.

public class phaxioResponse
    {
        public string success { get; set; }
        public string message { get; set; }
        public Dictionary<int,areaCode> data { get; set; }

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

Then:

    var res= JsonConvert.DeserializeObject<phaxioResponse>(json);
    Console.WriteLine(string.Join(",", res.data));


来源:https://stackoverflow.com/questions/23505096/deserialize-json-with-dynamic-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!