在反序列化期间选择两种不同类型

时间:2012-04-30 09:12:32

标签: c# json.net

我有一个可以有以下选择的对象:

"params": [23, 42]
"params": {"minuend": 42, "subtrahend": 23}

如何让json.net自动为第一个属性创建object[]属性,为第二个属性创建Dictionary<string,object>属性?

示例(存根)类:

[DataContract]
public class JsonRcpRequest
{
    [DataMember(Name = "params")]
    public object Parameters { get; set; }
}

1 个答案:

答案 0 :(得分:3)

解决方案是使用以下方法创建自定义JsonConverter

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

    //[42, 23]
    if (reader.TokenType == JsonToken.StartArray)
    {
        reader.Read();
        var values = new List<object>();
        while (reader.TokenType != JsonToken.EndArray)
        {
            values.Add(reader.Value);
            reader.Read();
        }

        reader.Read();
        source = values.ToArray();
    }
    else if (reader.TokenType == JsonToken.StartObject)//{"subtrahend": 23, "minuend": 42}
    {
        reader.Read();
        var values = new Dictionary<string, object>();
        while (reader.TokenType != JsonToken.EndObject)
        {
            if (reader.TokenType != JsonToken.PropertyName)
                throw new FormatException("Expected a property name, got: " + reader.TokenType);
            string propertyName = reader.Value.ToString();
            reader.Read();

            values.Add(propertyName, reader.Value);
            reader.Read();
        }

        source = values;
    }
    else
        throw new FormatException("Expected start of object or start of array");

    reader.Read();
    return source;
}

然后用它标记属性:

[DataMember(Name = "params", IsRequired = false)]
[JsonConverter(typeof(ArgumentConverter))]
public object[] Parameters { get; set; }