解析包含混合类型数组的奇怪JSON的最佳方法?

时间:2017-05-25 20:52:14

标签: c# .net json json.net

我正在通过websocket读取数据,数据以有效的JSON形式返回,但格式奇怪。

以下是返回数据的示例:

[1002,null,[98,"0.00011972","0.00012097","0.00011972","-0.16635331","38.03938952","305130.84018577",0,"0.00014363","0.00011168"]]

如何使用Json.NET将其转换为C#格式良好的类?

我理想的课程看起来像这样:

class Message
{
    int MessageId { get; set; }
    int? MessageVal { get; set; }
    Payload Payload { get; set; }
}
class Payload
{
    int PayloadId { get; set; }
    string Item1 { get; set; }
    string Item2 { get; set; }
    ...
    string Item8 { get; set; }
}

如何做到这一点? Hardmode:高效快捷

谢谢!

1 个答案:

答案 0 :(得分:2)

如果您无法控制返回给您的数据的形状,则可以使用以下内容:

班级定义:

public class Message
{
    public int MessageId { get; set; }
    public int? MessageVal { get; set; }
    public Payload Payload { get; set; }
}

public class Payload
{
    public int PayloadId { get; set; }
    public string[] Items { get; set;}
}

反序列化:

var json = @"[1002,null,[98,""0.00011972"",""0.00012097"",""0.00011972"",""-0.16635331"",""38.03938952"",""305130.84018577"",0,""0.00014363"",""0.00011168""]]";

var data = JArray.Parse(json);

var message = new Message()
{
    MessageId = data[0].ToObject<int>(),
    MessageVal = data[1].ToObject<int?>(),
    Payload = new Payload()
    {
        PayloadId = data[2][0].ToObject<int>(),
        Items = data[2].Skip(1).Select(x => x.ToString()).ToArray()
    }
};