使用Json.NET对包含数字键的反序列化JSON进行反序列化 [英] Deserialise JSON containing numeric key with Json.NET

查看:110
本文介绍了使用Json.NET对包含数字键的反序列化JSON进行反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下JSON(使用Json.NET)反序列化为一个对象,但是不能,因为类名需要以数字开头.

I would like to deserialize the following JSON (using Json.NET) to an object, but cannot, as the class name would need to begin with a number.

Wikipedia文章API 就是一个例子. 使用API 提供JSON响应会返回类似的内容.请注意"pages"键内的"16689396".

An example of this is the Wikipedia article API. Using the API to provide a JSON response returns something like this. Note the "16689396" inside the "pages" key.

{
   "batchcomplete":"",
   "continue":{
      "grncontinue":"0.893378504602|0.893378998188|35714269|0",
      "continue":"grncontinue||"
   },
   "query":{
      "pages":{
         "16689396":{
            "pageid":16689396,
            "ns":0,
            "title":"Jalan Juru",
            "extract":"<p><b>Jalan Juru</b> (Penang state road <i>P176</i>) is a major road in Penang, Malaysia.</p>\n\n<h2><span id=\"List_of_junctions\">List of junctions</span></h2>\n<p></p>\n<p><br></p>"
         }
      }
   }
}

我如何反序列化包含根据文章而更改的数字的JSON?

How could I deserialize this JSON containing a number which changes based on the article?

推荐答案

听起来像Query类中的Pages属性只需要是Dictionary<int, Page>Dictionary<string, Page>.

It sounds like the Pages property in your Query class would just need to be a Dictionary<int, Page> or Dictionary<string, Page>.

使用您提供的JSON的完整示例-我不得不猜测一些名称含义:

Complete example with the JSON you've provided - I've had to guess at some of the name meanings:

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

public class Root
{
    [JsonProperty("batchcomplete")]
    public string BatchComplete { get; set; }
    [JsonProperty("continue")]
    public Continuation Continuation { get; set; }
    [JsonProperty("query")]
    public Query Query { get; set; }
}

public class Continuation
{
    [JsonProperty("grncontinue")]
    public string GrnContinue { get; set; }
    [JsonProperty("continue")]
    public string Continue { get; set; }
}

public class Query
{
    [JsonProperty("pages")]
    public Dictionary<int, Page> Pages { get; set; }
}

public class Page
{
    [JsonProperty("pageid")]
    public int Id { get; set; }
    [JsonProperty("ns")]
    public int Ns { get; set; }
    [JsonProperty("title")]
    public string Title { get; set; }
    [JsonProperty("extract")]
    public string Extract { get; set; }
}

class Test
{
    static void Main()
    {
        string text = File.ReadAllText("test.json");
        var root = JsonConvert.DeserializeObject<Root>(text);
        Console.WriteLine(root.Query.Pages[16689396].Title);
    }    
}

这篇关于使用Json.NET对包含数字键的反序列化JSON进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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