网页前端设计

http://www.86y.org

搜索文章

C#解析复杂的 Json 字符串

用声音读出全文关注我吧
 2019/9/3 11:35:08 阅读次数:8160

如今大量的 Web API 为我们编写复杂程序提供了极大的方便,例如百度地图 API、图灵机器人 API等等,利用这些 Web 应用程序我们可以充分发挥云服务的优势,开发出大量有趣的应用。

Web API 通常返回 Json 或 XML 格式的检索数据,由于 Json 数据量更小,所以目前大多数情况下我们都选择返回 Json 格式的数据。

如果返回的 Json 文档很大,而我们仅仅需要其中的一小部分数据。按照之前的方法,我们必须首先定义一个与 Json 对象对应的 .NET 对象,然后反序列化,最后才能从对象中取出我们需要的数据。而有了 Json.NET,这个任务就很容易实现了,我们可以局部地解析一个 Json 对象。

下面以获取 Google 搜索结果为例,简单演示一下对复杂结构 Json 文档的解析。

string googleSearchText = @"{
  'responseData': {
    'results': [
      {
        'GsearchResultClass': 'GwebSearch',
        'unescapedUrl': 'http://en.wikipedia.org/wiki/Paris_Hilton',
        'url': 'http://en.wikipedia.org/wiki/Paris_Hilton',
        'visibleUrl': 'en.wikipedia.org',
        'cacheUrl': 'http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org',
        'title': 'Paris Hilton - Wikipedia, the free encyclopedia',
        'titleNoFormatting': 'Paris Hilton - Wikipedia, the free encyclopedia',
        'content': '[1] In 2006, she released her debut album...'
      },
      {
        'GsearchResultClass': 'GwebSearch',
        'unescapedUrl': 'http://www.imdb.com/name/nm0385296/',
        'url': 'http://www.imdb.com/name/nm0385296/',
        'visibleUrl': 'www.imdb.com',
        'cacheUrl': 'http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com',
        'title': 'Paris Hilton',
        'titleNoFormatting': 'Paris Hilton',
        'content': 'Self: Zoolander. Socialite Paris Hilton...'
      }
    ],
    'cursor': {
      'pages': [
        {
          'start': '0',
          'label': 1
        },
        {
          'start': '4',
          'label': 2
        },
        {
          'start': '8',
          'label': 3
        },
        {
          'start': '12',
          'label': 4
        }
      ],
      'estimatedResultCount': '59600000',
      'currentPageIndex': 0,
      'moreResultsUrl': 'http://www.google.com/search?oe=utf8&ie=utf8...'
    }
  },
  'responseDetails': null,
  'responseStatus': 200
}";

上面就是从 Google 搜索返回的 Json 数据,我们现在需要的是 responseData 属性下的 results 列表中结果,而且仅仅需要结果中的 title、content 和 url 属性值。

读取方式有两种,一种是定义Ilist,第二种则是转成数组直接输出需要的字段。

第一种:

public class SearchResult
{
    public string Title { get; set; }
    public string Content { get; set; }
    public string Url { get; set; }
}

//将 Json 文档解析为 JObject
JObject googleSearch = JObject.Parse(googleSearchText);
//将获得的 Json 结果转换为列表
IList results = googleSearch["responseData"]["results"].Children().ToList();
//将 Json 结果反序列化为 .NET 对象
IList searchResults = new List();
foreach(JToken result in results)
{
    SearchResult searchResult = JsonConvert.DeserializeObject(result.ToString());
    searchResults.Add(searchResult);
}

//输出结果:
// Title = Paris Hilton - Wikipedia, the free encyclopedia
// Content = [1] In 2006, she released her debut album...
// Url = http://en.wikipedia.org/wiki/Paris_Hilton

// Title = Paris Hilton
// Content = Self: Zoolander. Socialite Paris Hilton...
// Url = http://www.imdb.com/name/nm0385296/

第二种:

//将 Json 文档解析为 JObject
JObject googleSearch = JObject.Parse(googleSearchText);
//将获得的 Json 结果转换为列表
IList results = googleSearch["responseData"]["results"].Children().ToList();
//将 Json 结果转成数组类型输出
string outText="";
for (int i = 0; i < results.ToArray().Length; i++)
{
    outText+="Title ="+results[i].Title+" \n";
    outText+="Content ="+results[i].Content+" \n";
    outText+="Url ="+results[i].Url+" \n";
}

//输出结果:
// Title = Paris Hilton - Wikipedia, the free encyclopedia
// Content = [1] In 2006, she released her debut album...
// Url = http://en.wikipedia.org/wiki/Paris_Hilton

// Title = Paris Hilton
// Content = Self: Zoolander. Socialite Paris Hilton...
// Url = http://www.imdb.com/name/nm0385296/

个人感觉,第二种读取方式更灵活。

可以看到,对 Json 文档的解析基本分为以下几步:

  1. 1.将 Json 文档转换为 JObject 对象
  2. 2.使用JObject[属性]获取 JObject 对象中某个属性的值(JToken 格式)可以继续通过 JToken[属性] 获取属性内部的属性值(依然为 JToken 格式)
  3. 3.将 JToken 格式的属性值反序列化为 .NET 对象

(完)


大家有什么问题或技术上的想法可以在此与大家分享,也可以加入前端爱好者QQ群(141999928)一起学习进步:【幸凡前端技术交流群】
0

如果您觉得本文的内容对您的学习有所帮助,捐赠与共勉,支付宝(左)或微信(右)

阅读全文内容关闭