将字符串解析为可识别的数据结构的最佳方法

时间:2018-11-13 16:40:42

标签: c# json string parsing time-series

我有以下格式的数据。有一个可以读取时间序列的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]]}]"

这是来自rest服务的响应,旨在返回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似乎是Readings中的“ n”。 如何将其转换为有意义的东西?

1 个答案:

答案 0 :(得分:0)

从以下位置更改课程:

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);

Live Demo