[英]Handling JSON single object and array
我正在使用Newtonsoft.Json處理一些返回給我的JSON數據。 根據我的要求,我可以得到一些看起來像:
{
"TotalRecords":2,
"Result":
[
{
"Id":24379,
"AccountName":"foo"
},
{
"Id":37209,
"AccountName":"bar"
}
],
"ResponseCode":0,
"Status":"OK",
"Error":"None"
}
要么
{
"Result":
{
"Id":24379,
"AccountName":"foo"
},
"ResponseCode":0,
"Status":"OK",
"Error":"None"
}
因此,有時“結果”是結果數組,或者“結果”可能是單個響應。
我嘗試使用如何使用JSON.net處理同一屬性的單個項目和數組的答案,但我仍然得到錯誤。
特別是我得到了一個
Newtonsoft.json.jsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List'...
定制轉換器看起來像:
public class SingleOrArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objecType)
{
return (objecType == typeof(List<T>));
}
public override object ReadJson(JsonReader reader, Type objecType, object existingValue,
JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return token.ToObject<List<T>>();
}
return new List<T> { token.ToObject<T>() };
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
我的回復類看起來像
public class TestResponse
{
[JsonProperty("Result")]
[JsonConverter(typeof(SingleOrArrayConverter<string>))]
public List<DeserializedResult> Result { get; set; }
}
public class DeserializedResult
{
public string Id { get; set; }
public string AccountName { get; set; }
}
最后我的請求看起來像
List<TestResponse> list = JsonConvert.DeserializeObject<List<TestResponse>>(response.Content);
你的代碼很好,它只需要一些類型的調整。
這條線
List<TestResponse> list = JsonConvert.DeserializeObject<List<TestResponse>>(response.Content);
需要像這樣,因為你的響應是一個object
,而不是一個List
。
TestResponse list = JsonConvert.DeserializeObject<TestResponse>(response);
然后是您的自定義反序列化器屬性:
[JsonConverter(typeof(SingleOrArrayConverter<string>))]
需要成為:
[JsonConverter(typeof(SingleOrArrayConverter<DeserializedResult>))]
因為Result
對象不是string
或string
s數組,所以它是DeserializedResult
的數組或DeserializedResult
。
我認為,沒有辦法強調你應該采取何種類型的回應。 這就是為什么我建議檢查manualy類型的響應:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TestConsoleApp
{
public class Class1
{
public class Result
{
public int Id { get; set; }
public string AccountName { get; set; }
}
public class ModelWithArray
{
public int TotalRecords { get; set; }
public List<Result> Result { get; set; }
public int ResponseCode { get; set; }
public string Status { get; set; }
public string Error { get; set; }
}
public class Result2
{
public int Id { get; set; }
public string AccountName { get; set; }
}
public class ModelWithoutArray
{
public Result2 Result { get; set; }
public int ResponseCode { get; set; }
public string Status { get; set; }
public string Error { get; set; }
}
public static void Main(params string[] args)
{
//string json = "{\"TotalRecords\":2,\"Result\":[{\"Id\":24379,\"AccountName\":\"foo\"},{\"Id\":37209,\"AccountName\":\"bar\"}], \"ResponseCode\":0,\"Status\":\"OK\",\"Error\":\"None\"}";
string json = "{\"Result\":{\"Id\":24379,\"AccountName\":\"foo\"},\"ResponseCode\":0,\"Status\":\"OK\",\"Error\":\"None\"}";
if (checkIsArray(json))
{
ModelWithArray data = JsonConver.DeserializeObject<ModelWithArray >(json);
}else
{
ModelWithoutArray data = JsonConver.DeserializeObject<ModelWithoutArray>(json);
}
}
static bool checkIsArray(string json)
{
Dictionary<string, object> desData = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
if (desData["Result"].GetType().Name.Contains("Array"))
{
return true;
}
else
{
return false;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.