How to deserialize JSON with duplicate property names in the same object

后端 未结 3 1156
长发绾君心
长发绾君心 2020-11-29 12:24

I have a JSON string that I expect to contain duplicate keys that I am unable to make JSON.NET happy with.

I was wondering if anybody knows the best way (maybe usin

3条回答
  •  春和景丽
    2020-11-29 13:06

    Brian Rogers - Here is the helper function of the JsonConverter that I wrote. I modified it based on your comments about how a JsonTextReader is just a forward-reader doesn't care about duplicate values.

    private static object GetObject(JsonReader reader)
    {
        switch (reader.TokenType)
        {
            case JsonToken.StartObject:
            {
                var dictionary = new Dictionary();
    
                while (reader.Read() && (reader.TokenType != JsonToken.EndObject))
                {
                    if (reader.TokenType != JsonToken.PropertyName)
                        throw new InvalidOperationException("Unknown JObject conversion state");
    
                    string propertyName = (string) reader.Value;
    
                    reader.Read();
                    object propertyValue = GetObject(reader);
    
                    object existingValue;
                    if (dictionary.TryGetValue(propertyName, out existingValue))
                    {
                        if (existingValue is List)
                        {
                            var list = existingValue as List;
                            list.Add(propertyValue);
                        }
                        else
                        {
                            var list = new List {existingValue, propertyValue};
                            dictionary[propertyName] = list;
                        }
                    }
                    else
                    {
                        dictionary.Add(propertyName, propertyValue);
                    }
                }
    
                return dictionary;
            }
            case JsonToken.StartArray:
            {
                var list = new List();
    
                while (reader.Read() && (reader.TokenType != JsonToken.EndArray))
                {
                    object propertyValue = GetObject(reader);
                    list.Add(propertyValue);
                }
    
                return list;
            }
            default:
            {
                return reader.Value;
            }
        }
    }
    
        

    提交回复
    热议问题