如何将包含不同数据类型的JSON数组反序列化为单个对象 [英] How to deserialize a JSON array containing different data types to a single object
问题描述
最近几天,我一直在研究如何反序列化对C#对象的JSON响应. JSON有效,但我无法将任何JSON转换为C#转换器.我也找不到适用于此实例的Stackoverflow的答案. JSON响应为:
Over the last few days I have been researching on how to deserialize a JSON response to and C# object. The JSON is valid but I can not get any JSON to C# converters to convert it. I also cannot find an answer on Stackoverflow that works for this instance. The JSON Response is:
[
{
"SEX": "Male",
"BREED": "Opifex",
"PVPRATING": 1301,
"NAME": "Kilmanagh",
"FIRSTNAME": "Big",
"PVPTITLE": "Freshman",
"LASTNAME": "Kahuna",
"CHAR_DIMENSION": 5,
"ALIENLEVEL": 30,
"RANK_name": "Vindicator",
"HEADID": 40281,
"PROFNAME": "Guru",
"LEVELX": 220,
"PROF": "Martial Artist",
"CHAR_INSTANCE": 12734,
"SIDE": "Omni"
},
{
"ORG_DIMENSION": 5,
"RANK_TITLE": "President",
"ORG_INSTANCE": 9911,
"NAME": "Elements of Destruction",
"RANK": 0
},
"2016/04/06 08:37:26"
]
根据我的检查,它是一个包含两个对象和一个字符串的数组. 我已使用以下方法尝试将其转换为对象:
From my inspection it is an array that contains two objects and a string. I have used the following to attempt to convert it to an object:
resultArray = JsonConvert.DeserializeObject<List<JsonWhoisResult>>(data);
and
result = JsonConvert.DeserializeObject<JsonWhoisResult>(data);
无论哪种方式,我都会得到一个错误:
Either way I get an error:
转换值...(snip)... [ConsoleApplication6.JsonWhoisResult]时出错.路径",第1行,位置536.
Error converting value ...(snip)... [ConsoleApplication6.JsonWhoisResult]'. Path '', line 1, position 536.`
我不知道对象是否错误,或者我是否为此JSON格式使用了错误的代码.我正在使用:
I do not know if I have the object wrong, or if I am using incorrect code for this JSON format. I am using:
public class JsonWhoisResult
{
public stats stats { get; set; }
public header header { get; set; }
public string datetime { get; set; }
}
public class header
{
public int ORG_DIMENSION { get; set; }
public string RANK_TITLE { get; set; }
public int ORG_INSTANCE { get; set; }
public string NAME { get; set; }
public int RANK { get; set; }
}
public class stats
{
public string SEX { get; set; }
public string BREED { get; set; }
public int PVPRATING { get; set; }
public string NAME { get; set; }
public string FIRSTNAME { get; set; }
public string PVPTITLE { get; set; }
public string LASTNAME { get; set; }
public int CHAR_DIMENSION { get; set; }
public int ALIENLEVEL { get; set; }
public string RANK_name { get; set; }
public int HEADID { get; set; }
public string PROFNAME { get; set; }
public int LEVELX { get; set; }
public string PROF { get; set; }
public int CHAR_INSTANCE { get; set; }
public string SIDE { get; set; }
}
如果有人有任何解决方案,我将不胜感激.我还有其他几种使用这种类型的样式.如果我能找到解决方案,那么我应该可以将其应用于其余的解决方案.
If anyone has any solutions I would really appreciate it. I have several more that use this type of style. If I can get a solution then I should be able to apply it to the rest.
推荐答案
由于JSON是数组,因此无法反序列化为单个JsonWhoisResult
,并且由于数组包含不同的对象类型,因此无法直接反序列化为JsonConverter
来处理这种情况.转换器可以使用Json.Net的 LINQ-to-JSON API 进行反序列化JSON,然后手动将每个项目提取到其适当的对象类型,并根据需要填充单个JsonWhoisResult
.这样的事情应该起作用:
Because your JSON is an array you cannot deserialize into a single JsonWhoisResult
, and because your array contains disparate object types, you cannot deserialize directly into a List<JsonWhoisResult>
. You will need to make a custom JsonConverter
to handle this situation. The converter can use Json.Net's LINQ-to-JSON API to deserialize the JSON, then manually extract each item into its appropriate object type and populate a single JsonWhoisResult
as you want. Something like this should work:
class JsonWhoisResultConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(JsonWhoisResult));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray array = JArray.Load(reader);
JsonWhoisResult result = new JsonWhoisResult();
result.stats = array[0].ToObject<stats>();
result.header = array[1].ToObject<header>();
result.datetime = array[2].ToString();
return result;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
然后像这样使用它:
JsonWhoisResult result = JsonConvert.DeserializeObject<JsonWhoisResult>(json, new JsonWhoisResultConverter());
提琴: https://dotnetfiddle.net/d1hkCn
这篇关于如何将包含不同数据类型的JSON数组反序列化为单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!