Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c# - Deserialize JSON with dynamic objects

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"
        } [...]
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...