1

我一直在寻找几天,一次几个小时,试图找到我问题的答案。我有以下 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 库,但被困在“状态”部分。这就是促使我尝试 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# 知识还没有达到那个水平。我一直在尝试破译为回答类似问题而提供的解决方案,但得出的结论是我一定遗漏了一些东西。

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

4

1 回答 1

1

如果您使用的是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; }
}

文件结构

于 2014-10-20T05:36:45.843 回答