NewtonSoft.JSON官方手册中文版【连载13】

反序列化部分JSON片段

通常,在操作大型的JSON文档时,你可能只对一小段信息感兴趣。当你想把JSON片段反序列化为.NET对象时,这种情形可能会比较烦人,因为你不得不针对整个JSON结果定义.NET类。

利用Json.NET很容易变通地解决此问题。使用LINQ to JSON你可以先提取你想要反序列化的Json的小块,再把它们传给Json.NET序列化器。

片段对象

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

反序列化部分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': '<b>Paris Hilton</b> - 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': '<b>Paris Hilton</b>',
      'titleNoFormatting': 'Paris Hilton',
      'content': 'Self: Zoolander. Socialite <b>Paris Hilton</b>...'
    }
  ],
  '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
}";
JObject googleSearch = JObject.Parse(googleSearchText);
// get JSON result objects into a list
IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
// serialize JSON results into .NET objects
IList<SearchResult> searchResults = new List<SearchResult>();
foreach (JToken result in results)
{
  // JToken.ToObject is a helper method that uses JsonSerializer internally
  SearchResult searchResult = result.ToObject<SearchResult>();
  searchResults.Add(searchResult);
}
// Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia
// Content = [1] In 2006, she released her debut album...
// Url = http://en.wikipedia.org/wiki/Paris_Hilton
// Title = <b>Paris Hilton</b>
// Content = Self: Zoolander. Socialite <b>Paris Hilton</b>...
// Url = http://www.imdb.com/name/nm0385296/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值