Json.NET - 将多个对象属性自定义反序列化为单一类型的列表?

时间:2015-09-14 17:46:49

标签: c# json.net json-deserialization

我一直在努力想出最简单/最干净的方法来处理这个问题,并且在几个重构之后我就没有了。我希望有人可以提供帮助。

从我正在调用的服务返回的JSON是不可预测的并且不断更新。

示例:

{
    SomeKey : "SomeValue",
    SecondaryProperties: {
        Property1: { "Id" : "ABC", "Label" : "Property One", "Value" : 1 },
        Property2: { "Id" : "DEF", "Label" : "Property Two", "Value" : 10 },
        Property3: { "Id" : "GHI", "Label" : "Property Three", "Value" : 5 },
        Banana: { "Id" : "YUM", "Label" : "Property Four", "Value" : 5 },
        WeJustAddedThis: { "Id" : "XYZ", "Label" : "Property Five", "Value" : 1 }
    }
}

由于这些辅助属性键不断变化(注意:谢天谢地,这些值总是一致的!),创建一个具有属性的对象没有意义,因为我经常更新对象,除非我被告知新数据点已添加到API数据中,在代码更新之前,它永远不会出现在应用程序中。

所以我考虑创建一个自定义属性转换器,它会生成SecondaryProperty对象的列表。类似的东西:

public class SecondaryProperties {
    public string SomeKey { get; set; }
    [JsonConverter(typeof(SecondaryPropertyConverter))]
    public List<SecondaryProperty> PropertyList { get; set; }
}

public class SecondaryProperty {
    public string Id { get; set; }
    public string Label { get; set; }
    public int Value { get; set; }
}

// This is where things get hazy for me
public class SecondaryPropertyConverter: JsonConverter {
    ...
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        var ratings = new List<SecondaryProperty>();
        var obj = JObject.Load(reader);
        foreach(var property in obj.Properties()){
            var rating = property.Value<SecondaryProperty>();
            ratings.Add(rating);
        }
        return ratings;
    }  
}

我认为我走在正确的轨道上,但是列表总是空的,显然我错过了一些东西。任何人都可以提供一些见解吗?

非常感谢!

1 个答案:

答案 0 :(得分:3)

不需要任何花哨的东西,如果新项目都具有一致的模式,我们可以这样做:

void Main()
{
    var json=  @"{
    SomeKey : ""SomeValue"",
    SecondaryProperties: {
        Property1: { ""Id"" : ""ABC"", ""Label"" : ""Property One"", ""Value"" : 1 },
        Property2: { ""Id"" : ""DEF"", ""Label"" : ""Property Two"", ""Value"" : 10 },
        Property3: { ""Id"" : ""GHI"", ""Label"" : ""Property Three"", ""Value"" : 5 },
        Banana: { ""Id"" : ""YUM"", ""Label"" : ""Property Four"", ""Value"" : 5 },
        WeJustAddedThis: { ""Id"" : ""XYZ"", ""Label"" : ""Property Five"", ""Value"" : 1 }
    }
}"; 

    var result = JsonConvert.DeserializeObject<Root>(json);
}

public class Property
{

    [JsonProperty("Id")]
    public string Id { get; set; }

    [JsonProperty("Label")]
    public string Label { get; set; }

    [JsonProperty("Value")]
    public int Value { get; set; }
}



public class Root
{

    [JsonProperty("SomeKey")]
    public string SomeKey { get; set; }

    [JsonProperty("SecondaryProperties")]
    public Dictionary<string, Property> SecondaryProperties { get; set; }
}

Sample response