首页 > 解决方案 > 将字符串解析为可识别数据结构的最佳方法

问题描述

我有一些以下格式的数据。有一个读取时间序列的 uuid,每个元组代表一个时间戳和值。

"[{\"uuid\": \"3c24a849-3355-5b28-bf83-1e93c36eea75\", \"Readings\": [[1541524171000.0, 22.700000762939453], [1541531370000.0, 22.600000381469727], [1541577227000.0, 21.700000762939453], [1541578016000.0, 21.899999618530273], [1541578322000.0, 22.100000381469727], [1541580122000.0, 22.0]]}]"

这是来自旨在返回 json 的休息服务的响应。我继续做了

public class DataReading
{
    public string uuid { get; set; }
    public string readings { get; set; }
}

导入 Newtonsoft.Json 并做到了

var list = JsonConvert.DeserializeObject<List<DataReading>>(thereturnstring);

我收到一个错误

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Path '[0].Readings', line 1, position 63.'

有什么见解吗?第 1 行位置 63 似乎是读数中的“n”。我如何将其转换为有意义的东西?

标签: c#jsonstringparsingtime-series

解决方案


改变你的班级:

public class DataReading
{
    public string uuid { get; set; }
    public string readings { get; set; }
}

public class DataReading
{
    public string uuid { get; set; }
    public double[][] readings { get; set; }
}

然后你可以像反序列化它:

string jsonString = "[{\"uuid\": \"3c24a849-3355-5b28-bf83-1e93c36eea75\", \"Readings\": [[1541524171000.0, 22.700000762939453], [1541531370000.0, 22.600000381469727], [1541577227000.0, 21.700000762939453], [1541578016000.0, 21.899999618530273], [1541578322000.0, 22.100000381469727], [1541580122000.0, 22.0]]}]";
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<DataReading[]>(jsonString);

现场演示


推荐阅读