在JSON.NET中反序列化数组

时间:2012-06-12 20:40:20

标签: c# .net json serialization json.net

我有一个JSON输出,我需要反序列化为.NET对象:

{   "title": "Stock data",
    "raw_data": [
    [
      1088553600000,
      1.3635
    ],
    [
      1091232000000,
      1.3538
    ],
    [
      1093910400000,
      1.3563
    ]]
}

如果我正在使用JsonConvert,我应该如何构建我的类以使反序列化有效?

2 个答案:

答案 0 :(得分:1)

如果raw_data的类型都是双打的话,那么就像这样:

public class MyClass
{
    public string title { get; set; }
    public List<List<double>> raw_data { get; set; }
}

很酷的网站,您可能想看看:http://json2csharp.com/

答案 1 :(得分:0)

对不起,我原来的答案毫无价值,这是一个更好的答案。

你可能遇到了麻烦,因为你看到这些类型是一个整数和双精度值(C#程序员很自然),但是Json对这些类型一无所知,只是将数字表示为小数。

正如另一个答案所说,你可以简单地反序列化为双打列表。有趣的是,可以选择将其转换为更自然的表示形式。

但是,我不建议这样做,因为在反序列化时它不是完全类型安全的(转换为十进制时原始元素的类型会丢失,你只能假设这种方式有效)!

public class BarArrayConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        // Not properly implemented!
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        List<Bar> bars = new List<Bar>();

        // Read the first token after the start array
        reader.Read();

        // Parse elements of the array
        while (reader.TokenType == JsonToken.StartArray)
        {
            Bar b = new Bar();

            // Convert these as necessary to your internal structure. Note that they are nullable types.
            b.First = reader.ReadAsDecimal();
            b.Second = reader.ReadAsDecimal();


            // Read end array for this element
            reader.Read();
            // Pull off next array in list, or end of list
            reader.Read();

            bars.Add(b);
        }

        return bars;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}


class Bar
{
    public decimal? First;
    public decimal? Second;
}

class Foo
{
    [JsonProperty("title")]
    public string Title { get; set; }

    [JsonConverter(typeof(BarArrayConverter))]
    [JsonProperty("raw_data")]
    public List<Bar> RawData { get; set; }
}

使用小数类型几乎肯定更明智。我能看到这样做的唯一原因是,如果要求将第一个值保留为整数,这将是一种以更自然的方式限制变量值的方法。

相关问题