如何将JSON数组或JSON对象转换为对象列表?

时间:2017-03-17 11:22:24

标签: c# json.net

我尝试使用代码来创建自定义JSON转换器。

public class SingleValueArrayConverter<T> : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.StartObject)
        {                
            T instance = serializer.Deserialize<T>(reader);
            return new List<T>() { instance };
        }
        else if (reader.TokenType == JsonToken.StartArray)
        {
            return serializer.Deserialize<List<T>>(reader);
        }

        return null;
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

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

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

这是我的样本模型类。

  public class Foo
{
    [JsonProperty("type")]
    public string Type;
}

我使用以下代码执行。它会导致堆栈溢出错误。

var converter = new SingleValueArrayConverter<Foo>();

var test1 = "[{ \"type\": \"test\" }]";
var result1 = JsonConvert.DeserializeObject<List<Foo>>(test1, converter);

var test2 = "{ \"type\": \"test\" }";
var result2 = JsonConvert.DeserializeObject<List<Foo>>(test2, converter);

enter image description here

1 个答案:

答案 0 :(得分:0)

将任何JSON转换为.NET对象的最简单方法是使用JToken对象的“ToObject”方法。

public class FooConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);

        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<Foo>>();
        }

        var item = token.ToObject<Foo>();

        return new List<Foo> { item };
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

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

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

PS。 JToken对象是任何JSON数据的基类,因此我们可以将JToken对象转换为任何适当的类型。

JToken             - abstract base class     
   JContainer      - abstract base class of JTokens that can contain other JTokens
       JArray      - represents an JSON array (contains an ordered list of JTokens)
       JObject     - represents an JSON object (contains a collection of JProperties)
       JProperty   - represents a JSON property (a name/JToken pair inside a JObject)
   JValue          - represents a primitive JSON value (string, number, boolean, null)