反序列化JSON与动态对象 [英] Deserialize JSON with dynamic objects

查看:293
本文介绍了反序列化JSON与动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有自带的区号一长串的JSON对象。不幸的是每个区域代码是在数据对象列表中的对象名称。如何创建一个类,让RestSharp反序列化内容



下面是我的类现在看起来如何?



 公共类phaxioResponse 
{
公共字符串成功{搞定;组; }
公共字符串消息{搞定;组; }
公开名单<&AREACODE GT;数据{搞定;组; }

公共类AREACODE
{
公共字符串城市{搞定;组; }
公共字符串状态{搞定;组; }
}
}

和这里的JSON内容:

  {
成功:真正的
消息:277提供的区号。
数据:{
201:{
城:巴约讷,泽西市,市总工会
状态:新泽西
}
202: {
城:华盛顿
状态:区的哥
} [...]
}


解决方案

由于这JSON是不是C#友善,我不得不做两轮牛车一点点,使其走出正常。然而,结果是相当不错的。



  VAR JSON = JsonConvert.DeserializeObject<动态>(sampleJson); 
VAR数据=((JObject)json.data)。儿童();
变种的东西= data.Select(X =>'。'新{AREACODE = x.Path.Split()[1],市= x.First()[城市],国家= X。最后()状态]});

这代码将生成一个匿名类型最能代表该数据。然而,匿名类型可以很容易地通过男星一个比较正常的DTO类。



输出看起来取代是这样的:




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

解决方案

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:

这篇关于反序列化JSON与动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆