我从结构如下的 URL 获取字符串格式的 JSON,但我无法解析它。它抛出异常,知道如何解析它吗?
结构如下:
{
"pathway":{
"patients":{
"patient":[
{
"patientid":"7703176",
"name":"Abbot, Bud",
"status":"Invited",
"start":"2013-12-07",
"last":"N/A",
"engagement":"N/A",
"drug":"N/A",
"adherence":"N/A",
"vitals":"Current",
"last_appointment":"2013-10-25",
"next_appointment":"None"
},
{
"patientid":"5089554",
"name":"Brennan, Bonnie",
"status":"Connected",
"start":"2013-12-29",
"last":"2014-02-01",
"engagement":"Low",
"drug":" ",
"adherence":" ",
"vitals":"Out of Date",
"last_appointment":"2013-04-21",
"next_appointment":"None"
}
]
}
}
}
我是这样做的:
public class PathWayWrapper
{
public pathway pathway { get; set; }
}
和
public class pathway
{
public List<patient> patients { get; set; }
}
和
public class patient
{
public long patientid { get; set; }
public string name { get; set; }
public string status { get; set; }
public string start { get; set; }
public string last { get; set; }
public string engagement { get; set; }
public string drug { get; set; }
public string adherence { get; set; }
public string vitals { get; set; }
public string last_appointment { get; set; }
public string next_appointment { get; set; }
}
这是我的解析代码:
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
var Jsonobject = JsonConvert.DeserializeObject<PathWayWrapper>(json);
objPathway = Jsonobject.pathway;
最佳答案
您要反序列化的类不正确。您缺少“患者”类(class)。
当我有 JSON 并试图反序列化它时,我喜欢使用 http://json2csharp.com在反序列化类中生成第一次切割。它比尝试手动操作更准确。
var jsonobject = JsonConvert.DeserializeObject<RootObject>(json);
public class Patient
{
public string patientid { get; set; }
public string name { get; set; }
public string status { get; set; }
public string start { get; set; }
public string last { get; set; }
public string engagement { get; set; }
public string drug { get; set; }
public string adherence { get; set; }
public string vitals { get; set; }
public string last_appointment { get; set; }
public string next_appointment { get; set; }
}
public class Patients
{
public List<Patient> patient { get; set; }
}
public class Pathway
{
public Patients patients { get; set; }
}
public class RootObject
{
public Pathway pathway { get; set; }
}
附言您得到的异常通常是一个很好的线索,表明您定义反序列化类的方式有问题。
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ConsoleApplication1.Program+patient]' 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) 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.
关于c# - 如何在 C# 中解析/反序列化从 rest 服务返回的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21938920/