将 JSON 搜索结果反序列化为强类型列表 (JSON.NET)

Deserializing JSON search results into strongly typed lists (JSON.NET)

我在 JSON 中有搜索结果,我想将其反序列化为强类型对象

例如:

{
    searchresult: {
        resultscount: 15,
        results: [
            {
                resultnumber: 1,
                values: [
                    {
                        key:    "bookid",
                        value:  1424
                    },
                    {
                        key:    "name",
                        value:  "C# in depth"
                    },
                ]
            }
        ]
    }
}

我有这个 POCO

public class Book {
    public int BookId { get; set; }
    public string Name { get; set; }
}

我想要一份图书清单。是的,我可以为这种情况编写自己的自定义解串器,但我想使用默认的解串器。

是否可以这样做?

IEnumerable<Book> books = JsonConvert.DeserializeObject<IEnumerable<Book>>(json);
如果没有任何定制,

Json.NET 不会这样做。您有以下方法:

  1. Post 你的 类 到 http://json2csharp.com/ 创建你的 JSON 的文字表示,然后使用 Linq 将结果转换成列表Book 类:

    public class Value
    {
        public string key { get; set; }
        public string value { get; set; } // Type changed from "object" to "string".
    }
    
    public class Result
    {
        public int resultnumber { get; set; }
        public List<Value> values { get; set; }
    }
    
    public class Searchresult
    {
        public int resultscount { get; set; }
        public List<Result> results { get; set; }
    }
    
    public class RootObject
    {
        public Searchresult searchresult { get; set; }
    }
    

    然后

        var root = JsonConvert.DeserializeObject<RootObject>(json);
        var books = root.searchresult.results.Select(result => new Book { Name = result.values.Find(v => v.key == "name").value, BookId = result.values.Find(v => v.key == "bookid").value });
    
  2. 创建自定义 JsonConverter 以将 JSON 转换为正在读取的 POCO,例如:

    internal class BookConverter : JsonConverter
    {
        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }
    
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Book);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var values = serializer.Deserialize<List<KeyValuePair<string, string>>>(reader);
            if (values == null)
                return existingValue;
            var book = existingValue as Book;
            if (book == null)
                book = new Book();
            // The following throws an exception on missing keys.  You could handle this differently if you prefer.
            book.BookId = values.Find(v => v.Key == "bookid").Value;
            book.Name = values.Find(v => v.Key == "name").Value;
            return book;
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    
    public class Result
    {
        public int resultnumber { get; set; }
    
        [JsonProperty("values")] 
        [JsonConverter(typeof(BookConverter))]
        public Book Book { get; set; }
    }
    
    public class Searchresult
    {
        public int resultscount { get; set; }
        public List<Result> results { get; set; }
    }
    
    public class RootObject
    {
        public Searchresult searchresult { get; set; }
    }
    

    然后

        var root = JsonConvert.DeserializeObject<RootObject>(json);
        var books = root.searchresult.results.Select(result => result.Book);
    

    这里我只实现了 ReadJson 因为你的问题只问反序列化。如果需要,您可以类似地实施 WriteJson

  3. 使用 Linq to JSON to load the JSON into a structured hierarchy of JObject,然后使用 Linq 将结果转换为 Book

        var books = 
            JObject.Parse(json).Descendants()
                .OfType<JProperty>()
                .Where(p => p.Name == "values")
                .Select(p => p.Value.ToObject<List<KeyValuePair<string, string>>>())
                .Select(values => new Book { Name = values.Find(v => v.Key == "name").Value, BookId = values.Find(v => v.Key == "bookid").Value })
                .ToList();