簡體   English   中英

反序列化復雜的Json對象

[英]Deserializing complex Json objects

我想反序列化一個復雜的,並且說構造不好的json。 我編寫的代碼不會反序列化對象, MovieInfo屬性為null。 您可以在代碼中找到示例json。 我想避免使用JObject.Parsedynamic對象。 我在這里想念什么?

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

namespace ComplexJsonExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonInText = @"
            {
                ""movies"" : [
                    { 
                        ""Harry Potter"" : [
                            { ""rating"": ""great""}, 
                            { ""rating"": ""horrible""}
                        ]
                    },
                    { 
                        ""Guardians of the galaxy"" : [
                            { ""rating"": ""cool""}, 
                            { ""rating"": ""awesome""}
                        ]
                    }
                ]
            }
            ";

            var movieList = JsonConvert.DeserializeObject<MovieList>(jsonInText);
        }
    }

    public class MovieList
    {
        [JsonProperty("movies")]
        public IList<Movie> Movies { get; set; }
    }

    public class Movie
    {
        IDictionary<string, IList<MovieRating>> MovieInfo { get; set; }
    }

    public class MovieRating
    {
        [JsonProperty("rating")]
        public string Rating { get; set; }
    }
}

我認為這有點hack,但是它可以正常工作,並將json字符串反序列化為所需的格式:

class MovieConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Movie);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {            

        var movie = new Movie(){
            MovieInfo = new Dictionary<string,IList<MovieRating>>()
        };

        while (reader.Read() && reader.Value != null)
        {                
            var name = (string)reader.Value;

            reader.Read();

            var ratings = ((JArray)serializer.Deserialize(reader)).Values<string>("rating");

            movie.MovieInfo.Add(name, ratings.Select(r => new MovieRating(){ Rating = r}).ToList());
        }
        return movie;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

我確實必須對原始對象進行兩項更改,首先我將MovieInfo訪問MovieInfo公開,以便可以訪問它,其次添加JsonConverterAttribute

[JsonConverter(typeof(MovieConverter))]
public class Movie
{
    public IDictionary<string, IList<MovieRating>> MovieInfo { get; set; }
}

這有點丑陋,但您可以這樣做:

class MovieList
{
    [JsonProperty("movies")]
    public Movie[] Movies { get; set; }
}

class Movie : Dictionary<string, MovieRating[]>
{
}

class MovieRating
{
    [JsonProperty("rating")]
    public string Rating { get; set; }
}

奇怪的是,電影是只有一個鍵(其標題)的字典,但它與JSON結構匹配。 反序列化后,您始終可以將其映射到更明智的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM