以下解决方案使用 Json.NET。它首先将 JSON 字符串反序列化为 XML,然后使用 LINQ to XML 迭代所有人员节点并将它们转换为 Person 类的实例。
private class Person
{
public string ID { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
// deserializes your JSON and creates a list of Person objects from it
private void button1_Click(object sender, RoutedEventArgs e)
{
// your JSON
string json =
"{\"lastUpdated\":\"16:12\",\"filterOut\":[],\"people\": " +
"[{\"ID\":\"x\",\"Name\":\"x\",\"Age\":\"x\"},{\"ID\":\"x\",\"Name\":\"x\",\"Age\":\"x\"},{\"ID\":\"x\",\"Name\":\"x\",\"Age\":\"x\"}]," +
"\"serviceDisruptions\":" +
"{" +
"\"infoMessages\":" +
"[\"blah blah text\"]," +
"\"importantMessages\":" +
"[]," +
"\"criticalMessages\":" +
"[]" +
"}" +
"}";
// deserialize from JSON to XML
XDocument doc = JsonConvert.DeserializeXNode(json, "root");
// iterate all people nodes and create Person objects
IEnumerable<Person> people = from person in doc.Element("root").Elements("people")
select new Person()
{
ID = person.Element("ID").Value,
Name = person.Element("Name").Value,
Age = person.Element("Age").Value
};
// this is just demonstrating that it worked
foreach (Person person in people)
Debug.WriteLine(person.Name);
}
不要忘记导入:
using Newtonsoft.Json;
using System.Xml.Linq;
using System.Diagnostics;
这就是反序列化的 JSON 作为 XML 文档的样子(对于好奇的人来说):
<root>
<lastUpdated>16:12</lastUpdated>
<people>
<ID>x</ID>
<Name>x</Name>
<Age>x</Age>
</people>
<people>
<ID>x</ID>
<Name>x</Name>
<Age>x</Age>
</people>
<people>
<ID>x</ID>
<Name>x</Name>
<Age>x</Age>
</people>
<serviceDisruptions>
<infoMessages>blah blah text</infoMessages>
</serviceDisruptions>
</root>