【问题标题】:Deserialize JSON as object or array with JSON.Net [duplicate]使用 JSON.Net 将 JSON 反序列化为对象或数组 [重复]
【发布时间】:2016-06-28 22:50:07
【问题描述】:

我想知道是否可以反序列化一个可以是对象或数组的 JSON 对象。

与这个问题类似:Jackson deserialize object or array

但使用 JSON.Net。

示例

{
    "response": {
        "status":"success",
        // Could be either a single object or an array of objects.
        "data": {
            "prop":"value"
        }
        // OR
        "data": [
            {"prop":"value"},
            {"prop":"value"}
        ]
    }
}

【问题讨论】:

标签: c# json json.net


【解决方案1】:

我认为这可以解决您的问题

string jsonString= "your json string";
var token = JToken.Parse(jsonString);

if (token is JArray)
{
    IEnumerable<Car> cars= token.ToObject<List<Car>>();
}
else if (token is JObject)
{
    Car car= token.ToObject<Car>();
}

【讨论】:

  • JToken.Parse 正是我想要的。
【解决方案2】:

另一种方法是编写我们的 JsonConverter 并将其用于反序列化,以便我们可以在转换后使用静态类型。

class JsonDataConverter : JsonConverter
{
    public override bool CanWrite { get { return false; } }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Data);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.ReadFrom(reader);

        if (token is JArray)
            return new Data(token.Select(t => t["prop"].ToString()));
        if (token is JObject)
            return new Data(new[] { token["prop"].ToString() });
        throw new NotSupportedException();
    }

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

[JsonConverter(typeof(JsonDataConverter))]
class Data:List<string>
{
    public Data() : base() { }
    public Data(IEnumerable<string> data) : base(data) { }
}

class Response
{
    public string Status { get; set; }
    public Data Data { get; set; }
}

还有一个例子:

    class Program
    {
        static void Main(string[] args)
        {
            var inputObj = @"{
                     'response': {
                        'status':'success',
                        // Could be either a single object or an array of objects.
                        'data': { 'prop':'value'}

                                 }
                             }";

            var inputArray = @"{
                     'response': {
                         'status':'success',
                         // Could be either a single object or an array of objects.
                         'data':[
                                   { 'prop':'value'},
                                   { 'prop':'value'}
                                ]
                                 }
                              }";

            var obj = JsonConvert.DeserializeAnonymousType(inputObj, new { Response = new Response() });

            foreach(var prop in obj.Response.Data)
                Console.WriteLine(prop);

            var arr = JsonConvert.DeserializeAnonymousType(inputArray, new { Response = new Response() });

            foreach (var prop in arr.Response.Data)
                Console.WriteLine(prop);
        }
}

【讨论】:

  • 工作量很大,但这是最干净的解决方案。
【解决方案3】:

您可以将模型中“数据”的属性类型更改为动态或对象,并在运行时检查它是否为数组。

这是一个例子:

public class Response
{
    [JsonProperty("status")]
    public string Status { get; set; }
    [JsonProperty("data")]
    public dynamic Data { get; set; }
}


var response = JsonConvert.DeserializeJson<Response>(json);
.
.
.

Type responseDataType = response.Data.GetType();

if(responseDataType.IsArray) {
    // It's an array, what to do?
}
else {
    // Not an array, what's next?
}

【讨论】:

    猜你喜欢
    • 2015-12-05
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多