我一直在寻找几天,几小时试图找到我的问题的答案。我有以下的JSON字符串:在C#中使用Json.NET反序列化异构JSON数组
{
"id": "[email protected]",
"take": [{
"level": [0],
"status": [[3, [0]]]
}]
}
这是多种,我需要反序列化消息的样本,但它是导致我现在心痛的一个。对我来说有问题的部分是“状态”数组。我的类反序列化接受字符串的结果是:
[DataContract]
public class ReceivedMsg
{
public ReceivedMsg()
{
move = new List<MoveOperation>();
}
[DataMember]
public string id { get; set; }
[DataMember]
public List<MoveOperation> move { get; set; }
[DataContract]
public class Status
{
[DataMember]
public int destination { get; set; }
[DataMember]
public int[] source { get; set; }
}
[DataContract]
public class MoveOperation
{
public MoveOperation()
{
status = new List<Status>();
}
[DataMember]
public int[] level;
[DataMember]
public List<Status> status { get; set; }
}
}
的代码做反序列化是:
ReceivedMsg m = new ReceivedMsg();
m = JsonConvert.DeserializeObject<ReceivedMsg>(strResp, new JsonSerializerSettings { TraceWriter = traceWriter });
哪里strResp是字符串方含JSON数据。
我最初尝试使用.NET框架的一部分的JSON库,但卡在“状态”部分。这就是促使我尝试使用Json.NET的原因。
我得到的错误是:
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Roper.Roper+ReceivedMsg+Status' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'move[0].status[0]', line 6, position 16.
任何帮助将不胜感激。当然,我会很乐意根据需要提供更多信息。我试过做一个自定义转换器,但我认为我的C#知识还没有达到那个水平。我一直试图破译所提供的解决方案来回答类似的问题,但总结说我必须错过一些东西。
我真诚感谢社区花时间阅读我冗长的问题。你的慷慨持续令我惊叹!
通过你的代码,它似乎并不像你使用JSON.NET。这是纯粹的.NET和JSON。这是JSON.NET:https://www.nuget.org/packages/Newtonsoft.Json/ – BrunoLM 2014-10-20 05:34:04