我有一个JSON文件,例如:
{
"samples":[
{
"date":"2014-08-10T09:00:00Z",
"temperature":10,
"pH":4,
"phosphate":4,
"chloride":4,
"nitrate":10
},
{
"date":"2014-08-12T09:05:00Z",
"temperature":10.5,
"pH":5,
"chloride":4,
"phosphate":4
},
{
"date":"2014-08-14T09:02:00Z",
"temperature":10.8,
"pH":3,
"phosphate":4
},
{
"date":"2014-08-16T09:02:00Z",
"temperature":11.2,
"pH":6,
"chloride":4
},
{
"date":"2014-08-18T08:58:00Z",
"temperature":10.9,
"pH":10,
"chloride":4,
"phosphate":4,
"nitrate":10
},
{
"date":"2014-08-20T09:10:00Z",
"temperature":9.3,
"pH":6,
"phosphate":4
},
{
"date":"2014-08-22T09:01:00Z",
"temperature":9.5,
"pH":10,
"chloride":4,
"phosphate":4,
"nitrate":10
}
]
}
我需要访问每个子元素,例如“温度”,“ pH”等,以计算它们的平均值。为此,我想使用反序列化器。首先,我创建了一个自定义类来保存json的参数,
public class SampleClass
{
public float temperature { get; set; } = 0;
public int pH { get; set; } = 0;
public int phosphate { get; set; } = 0;
public int chloride { get; set; } = 0;
public int nitrate { get; set; } = 0;
}
紧接着,我使用此自定义类应用了反序列化器;
List<SampleClass> json = JsonConvert.DeserializeObject<List<SampleClass>>(jsonStr);
使用上面的代码行,我遇到了错误;
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[GeneralKnowledge.Test.App.Tests.SampleClass]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'samples', line 2, position 14.
您会建议我解决什么问题?预先感谢。
答案 0 :(得分:2)
假设您的JSON如下:
{
"samples":[ ... ]
}
您有一个外部容器对象,该对象封装了样本数组。您需要反序列化为反映此结构的数据模型。一种简单的方法是使用匿名对象以及JsonConvert.DeserializeAnonymousType()
:
var result = JsonConvert.DeserializeAnonymousType(jsonStr, new { samples = default(List<SampleClass>) })
.samples;
这种方法避免将JSON加载到中间的dynamic
或JToken
表示形式中。
提琴here。
答案 1 :(得分:1)
尝试一下:
dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(json_string);
List<SampleClass> result = JsonConvert.DeserializeObject<List<SampleClass>>(json.samples.ToString());
但如果没有,请使用此
List<SampleClass> result = new List<SampleClass>();
foreach (var item in json.samples)
{
result.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<SampleClass>(item.ToString()));
}