Deserialize JSON with dynamic objects

后端 未结 4 949
梦毁少年i
梦毁少年i 2020-12-11 02:41

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 wi

4条回答
  •  不思量自难忘°
    2020-12-11 02:43

    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(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

提交回复
热议问题