规范化4种类型之间的JSON参数

时间:2016-08-22 14:28:44

标签: c# json.net

我有一个参数的4种可能结果,我想将其标准化为List<ResponseModel>

输入1:

{
    "err": 0,
    "misc": "stringGoesHere",
    "otherMisc": "stringGoesHere",
    "responseModel": [
        "responseModel1" : {
            //Stuff I want
        },
        "responseModel2" : {
            //Stuff I want
        }
    ]
}

输入2:

{
    "err": 0,
    "misc": "stringGoesHere",
    "otherMisc": "stringGoesHere",
    "responseModel": [
        "oldResponseModel1" : {
            //Stuff I want
        },
        "oldResponseModel2" : {
            //Stuff I want
        }
    ]
}

输入3:

{
    "err": 0,
    "misc": "stringGoesHere",
    "otherMisc": "stringGoesHere",
    "responseModel":  {
            //Stuff I want
    }
}

我已尝试使用Json.net JsonConverter进行反序列化,我可以使第一个input2工作,但尝试使用SelectAll会在StackOverflow异常中结束。

我的转化覆盖看起来像这样:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    List<T> result = new List<T>();
    // object only
    if (reader.TokenType == JsonToken.StartObject)
    {
        T instance = (T)serializer.Deserialize(reader, typeof(T));
        result = new List<T>() { instance };
    }
    // list of objects
    else if (reader.TokenType == JsonToken.StartArray)
    {
        try
        {
            List<T> stillArray = serializer.Deserialize<List<T>>(reader).ToList();
        }
        catch (Exception)
        {
            throw;
        }
    }
    return result;
}

但是,stillArray以StackOverflow异常结束。这次转换我错过了什么?

0 个答案:

没有答案