反序列化可以具有不同类型的属性名称

时间:2020-04-04 19:39:49

标签: c# json .net-core json.net

我从提供商那里收到数据,看起来像这样:

{
    "data": [
        {
            "propertyNames":[
                {
                    "a":"a1",
                    "b":"b1",
                    ...
                    "z":"z1"
                },
                {
                    "a":"a2",
                    "b":"b2",
                    ...
                    "z":"z2"
                },
            ],
            ...
            "otherProperty": "abc"
        },
        {
            "propertyNames":{
                "1": {
                    "a":"a1",
                    "b":"b1",
                    ...
                    "z":"z1"
                },
                "2": {
                    "a":"a2",
                    "b":"b2",
                    ...
                    "z":"z2"
                },
            },
            ...
            "otherProperty": "bce"
        }
    ]
}

实际上,propertyNames可以是以下类型:

[JsonProperty("propertyNames")]
Dictionary<string, MyObject> PropertyNames {get;set;}

[JsonProperty("propertyNames")]
List<MyObject> PropertyNames {get;set;}

我该如何反序列化?

2 个答案:

答案 0 :(得分:2)

您实际上有多种选择。

例如,您可以使用JObject作为类型

[JsonProperty("propertyNames")]
JObject PropertyNames {get;set;}

不幸的是,您将不得不写下复杂的逻辑来解析其中的信息。

您还可以创建自定义JsonConverter

public class DynamicTypeConverter: JsonConverter<DynamicType>
{
    public override void WriteJson(JsonWriter writer, Version value, JsonSerializer serializer)
    {
    }

    public override DynamicType ReadJson(JsonReader reader, Type objectType, Version existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var obj = new DynamicType();
        // Least fun part, compute & assign values to properties
        // Logic depends if you are going to use JObject.Load(reader) or reader.Read() with reader.Value and TokenType
        return obj;
    }
}

public class DynamicType
{
  Dictionary<string, MyObject> PropertyNamesDict {get;set;}
  List<MyObject> PropertyNamesList {get;set;}
}

答案 1 :(得分:2)

假设"propertyNames"对象中的属性名称都是整数,则可以使用this answerDisplay JSON object array in datagridviewListToDictionaryConverter<T>如下定义数据模型:

数据模型:

public class MyObject
{
    public string a { get; set; }
    public string b { get; set; }
    public string z { get; set; }
}

public class Datum
{
    [JsonConverter(typeof(ListToDictionaryConverter<MyObject>))]
    public List<MyObject> propertyNames { get; set; }
    public string otherProperty { get; set; }
}

public class RootObject
{
    public List<Datum> data { get; set; }
}

转换器按原样复制,没有任何修改。它将转换JSON对象

{
   "1":{
      "a":"a1",
      "b":"b1",
      "z":"z1"
   },
   "2":{
      "a":"a2",
      "b":"b2",
      "z":"z2"
   }
}

转换为List<MyObject>,其值分别位于索引1和2,null的索引为零。

演示小提琴#1 here

或者,如果您希望propertyNames的类型为Dictionary<int, MyObject>,则可以按以下方式修改模型和转换器:

public class Datum
{
    [JsonConverter(typeof(IntegerDictionaryToListConverter<MyObject>))]
    public Dictionary<int, MyObject> propertyNames { get; set; }
    public string otherProperty { get; set; }
}

public class IntegerDictionaryToListConverter<T> : JsonConverter where T : class
{
    // From this answer https://stackoverflow.com/a/41559688/3744182
    // To https://stackoverflow.com/questions/41553379/display-json-object-array-in-datagridview
    public override bool CanConvert(Type objectType)
    {
        return typeof(Dictionary<int, T>).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var dictionary = existingValue as IDictionary<int, T> ?? (IDictionary<int, T>)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
        if (reader.TokenType == JsonToken.StartObject)
            serializer.Populate(reader, dictionary);
        else if (reader.TokenType == JsonToken.StartArray)
        {
            var list = serializer.Deserialize<List<T>>(reader);
            for (int i = 0; i < list.Count; i++)
                dictionary.Add(i, list[i]);
        }
        else
        {
            throw new JsonSerializationException(string.Format("Invalid token {0}", reader.TokenType));
        }
        return dictionary;
    }

    public override bool CanWrite { get { return false; } }

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

演示小提琴#2 here

如果属性名称并非总是整数,则可以稍微修改转换器以反序列化为Dictionary<string, T>

相关问题