我正在访问JSON格式的API调用中的数据。我正在试着把它放在字典里,这样我就可以访问数据了。这对于简单的JSON对象非常有效,但是对于具有“在解析值时遇到意外字符:[. Path‘cluster_function’,行1,位置539”的嵌套对象则失败。
我的JSON:
{
"id": "xxxxx",
"uuid": "xxxxx",
"cluster_incarnation_id": 151013752,
"cluster_functions": ["NDFS"],
"is_lts": true,
"num_nodes": 4,
"block_serials": ["17xxx"],
"ntp_servers": ["172.26.140.50", "ntp.xxx.be"],
"service_centers": [],
"http_proxies": [],
"rackable_units": [{
"id": 23,
"rackable_unit_uuid": "09f211d1-8fb4-xxxx-86e2-ce819xxxx29",
"positions": ["1", "2", "3", "4"],
"nodes": [6, 7, 8, 9]
}],
"public_keys": [],
"smtp_server": null,
"hypervisor_types": ["kKvm"],
"cluster_redundancy_state": {
"current_redundancy_factor": 2,
"desired_redundancy_factor": 2,
"redundancy_status": {
"kCassandraPrepareDone": true,
"kZookeeperPrepareDone": true
}
}
}代码:
using (StreamReader reader = new StreamReader(HttpResponseStream))
{
//Response.Code = 1;
string body = reader.ReadToEnd();
consoleoutput("REST: result" + body);
resultdict = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
}我不确定如何继续。我是否应该逐行解析,如果值不是字符串,则执行另一次反序列化?但是,如果我事先不知道JSON的格式(以及级别的数量),我该怎么做呢?
或者,有没有一种更有效的方法来解析一个字典,而不管有多少层?
谢谢
发布于 2019-05-27 17:52:33
尝试:
using (StreamReader reader = new StreamReader(HttpResponseStream))
{
//Response.Code = 1;
string body = reader.ReadToEnd();
consoleoutput("REST: result" + body);
resultdict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(body);
}不管怎么说,你不应该这样做。
您应该创建一个类来描述每个可能的属性,并像这样工作:
public class Entity { /* properties definitions... */ }然后
using (StreamReader reader = new StreamReader(HttpResponseStream))
{
//Response.Code = 1;
string body = reader.ReadToEnd();
consoleoutput("REST: result" + body);
List<Entity> entities = JsonConvert.DeserializeObject<Entity>(body).ToList();
}https://stackoverflow.com/questions/56323601
复制相似问题