使用自定义解串器与JSON.Net反序列化JSON [英] Deserializing JSON using custom deserializer with JSON.Net

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

问题描述

我有JSON看起来像这样的:

  {
MobileSiteContents:{
AU / EN:
http://www.url1.com,
http://www.url2.com,

],
CN / ZH:
http://www.url2643.com,

]
}
}

我试图把它反序列化到的,看起来类的的IEnumerable 像这样的:

 公共类MobileSiteContentsContentSectionItem:ContentSectionItem 
{
公共字符串[]网址{搞定;组; }
}

公共抽象类ContentSectionItem
{
公共字符串文化{搞定;组; }
}



这可能吗?结果
我知道我会可能需要使用自定义JsonConverter这一点,但无法找到任何的例子。



我开始写的方法使用转换 JObject.Parse 但不知道这是否是正确的/最快捷的路线走了下来:

 公开的IEnumerable< MobileSiteContentsContentSectionItem>解析(JSON字符串)
{
VAR jobject = JObject.Parse(JSON);

VAR的结果=新的List< MobileSiteContentsContentSectionItem>();

的foreach
{
VAR文化= item.Path(以jobject.Children()VAR项目);
的String [] =的URL新的[] {}; // =这是我在troble这里的一部分...

result.Add(新MobileSiteContentsContentSectionItem {=文化文化的url =网址});
}

返回结果;
}


解决方案

您是在右边跟踪。下面是纠正你需要:




  1. 您是在期望得到,实际上是数据的顶级对象的子迭代在进一步下跌的对象一个级别。您需要导航到的的的 MobileSiteContents 属性和迭代的孩子们。

  2. 当你把儿童() JObject ,使用,让你投他们过载 JProperty 对象;这将使它更容易提取所需的数据。

  3. 获得文化名称 JProperty 项目

  4. 的要获得网​​址,获得 JProperty 项目的,并使用 ToObject<字符串[]> ()将其转换为一个字符串数组



下面是更正后的代码:

 公开的IEnumerable< MobileSiteContentsContentSectionItem>解析(JSON字符串)
{
VAR jObject = JObject.Parse(JSON);

VAR的结果=新的List< MobileSiteContentsContentSectionItem>();

的foreach(在jObject [MobileSiteContents]子< VAR项目。JProperty>())
{
VAR文化= item.Name;
的String [] =网址:item.Value.ToObject LT;字符串[]>();

result.Add(新MobileSiteContentsContentSectionItem {=文化文化的url =网址});
}

返回结果;
}

如果你喜欢简洁的代码,你可以这样减少了单行

 公开的IEnumerable< MobileSiteContentsContentSectionItem>解析(字符串JSON)
{
返回JObject.Parse(JSON)[MobileSiteContents]
。孩子< JProperty>()
。选择(道具=>新建MobileSiteContentsContentSectionItem
{
区域性= prop.Name,
的url = prop.Value.ToObject<字符串[]>()
})
.ToList();
}



演示:

 类节目
{
静态无效的主要(字串[] args)
{
串JSON = @
{
MobileSiteContents:{
,AU / EN:
http://www.url1.com,
的http:/ /www.url2.com,
],
,CN / ZH:
http://www.url2643.com,
]
}
};

的foreach
{
Console.WriteLine(item.Culture)(在解析(JSON)MobileSiteContentsContentSectionItem项目);
的foreach(在item.Urls字符串URL)
{
Console.WriteLine(+网址);
}
}
}

公共静态的IEnumerable< MobileSiteContentsContentSectionItem>解析(字符串JSON)
{
返回JObject.Parse(JSON)[MobileSiteContents]
。孩子< JProperty>()
。选择(道具=>新建MobileSiteContentsContentSectionItem ()
{
区域性= prop.Name,
的url = prop.Value.ToObject<字符串[]>()
})
.ToList() ;
}

公共类MobileSiteContentsContentSectionItem:ContentSectionItem
{
公共字符串[]网址{搞定;组; }
}

公共抽象类ContentSectionItem
{
公共字符串文化{搞定;组; }
}
}



输出:

  AU / EN 
http://www.url1.com
http://www.url2.com
CN / ZH
http://www.url2643.com


I have JSON that looks like this:

{
  "MobileSiteContents": {
    "au/en": [
      "http://www.url1.com",
      "http://www.url2.com",

    ],
    "cn/zh": [
      "http://www.url2643.com",

    ]
  }
}

I'm trying to deserialize it into an IEnumerable of classes that look like this:

public class MobileSiteContentsContentSectionItem : ContentSectionItem
{
    public string[] Urls { get; set; }
}

public abstract class ContentSectionItem
{
    public string Culture { get; set; }
}

Is that possible?
I realise I will probably need to use a Custom JsonConverter for this, but can't find any examples.

I started writing a method to convert using JObject.Parse but not sure if this is the correct / most efficient route to go down:

public IEnumerable<MobileSiteContentsContentSectionItem> Parse(string json)
{
    var jobject = JObject.Parse(json);

    var result = new List<MobileSiteContentsContentSectionItem>();

    foreach (var item in jobject.Children())
    {
        var culture = item.Path;
        string[] urls = new[] { "" }; //= this is the part I'm having troble with here...

        result.Add(new MobileSiteContentsContentSectionItem { Culture = culture, Urls = urls });
    }

    return result;
}

解决方案

You're on the right track. Here are the corrections you need to make:

  1. You're iterating over children of the top-level object expecting to get data that is actually in an object one level further down. You need to navigate to the value of the MobileSiteContents property and iterate over the children of that.
  2. When you take the Children() of the JObject, use the overload that lets you cast them to JProperty objects; that will make it much easier to extract the data you want.
  3. Get the culture from the Name of the JProperty item
  4. To get the urls, get the Value of the JProperty item and use ToObject<string[]>() to convert it to a string array.

Here is the corrected code:

public IEnumerable<MobileSiteContentsContentSectionItem> Parse(string json)
{
    var jObject = JObject.Parse(json);

    var result = new List<MobileSiteContentsContentSectionItem>();

    foreach (var item in jObject["MobileSiteContents"].Children<JProperty>())
    {
        var culture = item.Name;
        string[] urls = item.Value.ToObject<string[]>();

        result.Add(new MobileSiteContentsContentSectionItem { Culture = culture, Urls = urls });
    }

    return result;
}

If you like terse code, you can reduce this to a "one-liner":

public IEnumerable<MobileSiteContentsContentSectionItem> Parse(string json)
{
    return JObject.Parse(json)["MobileSiteContents"]
        .Children<JProperty>()
        .Select(prop => new MobileSiteContentsContentSectionItem
        {
            Culture = prop.Name,
            Urls = prop.Value.ToObject<string[]>()
        })
        .ToList();
}

Demo:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""MobileSiteContents"": {
                ""au/en"": [
                    ""http://www.url1.com"",
                    ""http://www.url2.com"",
                ],
                ""cn/zh"": [
                    ""http://www.url2643.com"",
                ]
            }
        }";

        foreach (MobileSiteContentsContentSectionItem item in Parse(json))
        {
            Console.WriteLine(item.Culture);
            foreach (string url in item.Urls)
            {
                Console.WriteLine("  " + url);
            }
        }
    }

    public static IEnumerable<MobileSiteContentsContentSectionItem> Parse(string json)
    {
        return JObject.Parse(json)["MobileSiteContents"]
            .Children<JProperty>()
            .Select(prop => new MobileSiteContentsContentSectionItem()
            {
                Culture = prop.Name,
                Urls = prop.Value.ToObject<string[]>()
            })
            .ToList();
    }

    public class MobileSiteContentsContentSectionItem : ContentSectionItem
    {
        public string[] Urls { get; set; }
    }

    public abstract class ContentSectionItem
    {
        public string Culture { get; set; }
    }
}

Output:

au/en
  http://www.url1.com
  http://www.url2.com
cn/zh
  http://www.url2643.com

这篇关于使用自定义解串器与JSON.Net反序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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