我想反复化一个复合体,让我们说构造不好的json。我写的代码没有反序列化对象,MovieInfo
属性为null。您可以在代码中找到示例json。我想避免使用JObject.Parse
和dynamic
个对象。我在这里缺少什么?
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; }
}
}
答案 0 :(得分:1)
我认为这有点像黑客,但它可以工作,并将你的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
公开设置了访问权限,以便我可以访问它,然后再添加JsonConverterAttribute
:
[JsonConverter(typeof(MovieConverter))]
public class Movie
{
public IDictionary<string, IList<MovieRating>> MovieInfo { get; set; }
}
答案 1 :(得分:1)
这有点难看,但你可以这样做:
class MovieList
{
[JsonProperty("movies")]
public Movie[] Movies { get; set; }
}
class Movie : Dictionary<string, MovieRating[]>
{
}
class MovieRating
{
[JsonProperty("rating")]
public string Rating { get; set; }
}
很奇怪电影是一个只有一个键(它的标题)的字典,但它与JSON结构相匹配。反序列化后,您始终可以将其映射到更合理的位置。