Deserialise JSON containing numeric key with Json.NET

后端 未结 3 1994
孤街浪徒
孤街浪徒 2021-01-14 18:50

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.

An example of this is

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-14 19:18

    It sounds like the Pages property in your Query class would just need to be a Dictionary or Dictionary.

    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 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(text);
            Console.WriteLine(root.Query.Pages[16689396].Title);
        }    
    }
    

提交回复
热议问题