[英]Deserializing a heterogeneous JSON array using Json.NET
我一直在搜索数天,一次数小时,试图找到我的问题的答案。 我有以下 JSON 字符串:
{
"id": "658@787.000a35000122",
"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 数据的字符串。
我最初尝试使用 JSON 库,它是 .NET 框架的一部分,但卡在了“状态”部分。 这就是促使我尝试 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 (如果不是,您可以使用 NuGet 包管理器安装它)
PM> Install-Package Newtonsoft.Json
这应该会为您指明正确的方向:)
void Main()
{
string json = @"{
""id"": ""658@787.000a35000122"",
""take"": [{
""level"": [0],
""status"": [[3, [0]]]
}]
}";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
}
public class Take
{
[JsonProperty("level")]
public int[] Level { get; set; }
[JsonProperty("status")]
public object[][] Status { get; set; }
}
public class RootObject
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("take")]
public Take[] Take { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.