简体   繁体   中英

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

I have search results in JSON and I want to deserialize it into strongly typed objects

For example:

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

And I have this POCO

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

I want to get a list of books. Yes, I can write my own custom deserializer for this case, but I want to use a default deserializer.

Is it possible to do something like that?

IEnumerable<Book> books = JsonConvert.DeserializeObject<IEnumerable<Book>>(json);

Json.NET will not do this without any customization. You have the following approaches:

  1. Post your classes to http://json2csharp.com/ to create a literal representation of your JSON, then use Linq to transform the result into a list of Book classes:

     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; } } 

    And then

      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. Create a custom JsonConverter to convert the JSON to your POCO as it is being read, for instance:

     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; } } 

    and then

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

    Here I only implemented ReadJson as your question only asks about deserialization . You could implement WriteJson similarly if required.

  3. Use Linq to JSON to load the JSON into a structured hierarchy of JObject 's then convert the result to Book 's with Linq:

      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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM