[英]How to deserialize a JSON array containing different data types to a single object
Over the last few days I have been researching on how to deserialize a JSON response to and C# object. 在过去的几天里,我一直在研究如何将JSON响应反序列化为C#对象。 The JSON is valid but I can not get any JSON to C# converters to convert it.
JSON是有效的但我无法获得任何JSON到C#转换器来转换它。 I also cannot find an answer on Stackoverflow that works for this instance.
我也找不到适用于此实例的Stackoverflow的答案。 The JSON Response is:
JSON响应是:
[
{
"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: 无论哪种方式我都会收到错误:
Error converting value ...(snip)... [ConsoleApplication6.JsonWhoisResult]'.
转换值时出错......(剪辑)... [ConsoleApplication6.JsonWhoisResult]'。 Path '', line 1, position 536.`
路径'',第1行,第536位
I do not know if I have the object wrong, or if I am using incorrect code for this JSON format. 我不知道我是否有错误的对象,或者我是否使用了这种JSON格式的错误代码。 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.
如果我能得到解决方案,那么我应该能够将其应用到其余部分。
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>
. 因为您的JSON是一个数组,所以不能反序列化为单个
JsonWhoisResult
,并且因为您的数组包含不同的对象类型,所以不能直接反序列化为List<JsonWhoisResult>
。 You will need to make a custom JsonConverter
to handle this situation. 您需要制作一个自定义
JsonConverter
来处理这种情况。 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. 转换器可以使用Json.Net的LINQ-to-JSON API对JSON进行反序列化,然后手动将每个项目提取到适当的对象类型中,并根据需要填充单个
JsonWhoisResult
。 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();
}
}
Then use it like this: 然后像这样使用它:
JsonWhoisResult result = JsonConvert.DeserializeObject<JsonWhoisResult>(json, new JsonWhoisResultConverter());
Fiddle: https://dotnetfiddle.net/d1hkCn 小提琴: https : //dotnetfiddle.net/d1hkCn
You can use JSON.net's support for dynamic
to do this. 您可以使用JSON.net对
dynamic
的支持来执行此操作。 I just tested this with the JSON as you pasted it above , and it works - but note, this is not strongly typed. 我刚刚在上面粘贴时用JSON对它进行了测试,但是它有效 - 但请注意,这不是强类型的。
dynamic result = JsonConvert.DeserializeObject(json);
// value is "Freshman"
Console.WriteLine("result[0].PVPTITLE = '{0}'", result[0].PVPTITLE);
// value is "President"
Console.WriteLine("result[1].RANK_TITLE = '{0}'", result[1].RANK_TITLE);
// value is 2016-04-06 08:37:27
Console.WriteLine("result[2] '{0}'", (DateTime)result[2]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.