使用Json.NET在C#中反序列化异构JSON数组

时间:2014-10-20 04:56:25

标签: c# arrays json json.net heterogeneous

我一直在寻找几天,几小时试图找到我的问题的答案。我有以下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数据的字符串。

我最初尝试使用作为.NET框架一部分的JSON库,但却陷入了&#34;状态&#34;一部分。是什么促使我尝试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#知识还没达到那个级别。我一直试图破译为回答类似问题而提供的解决方案,但总结说我必须遗漏一些东西。

衷心感谢社区花时间阅读我冗长的问题。你的慷慨继续令我惊讶!

1 个答案:

答案 0 :(得分:0)

如果你正在使用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; }
}

File structure