4

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

"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; }
}
4

1 回答 1

6

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; }
于 2012-05-02T10:39:22.243 回答