gpt4 book ai didi

c# - 在 WP7 中反序列化 JSON

转载 作者:太空狗 更新时间:2023-10-29 23:02:11 25 4
gpt4 key购买 nike

我有这个 JSON,我想在 Windows Phone 上阅读它。我一直在玩 DataContractJsonSerializer 和 Json.NET 但运气不佳,尤其是阅读每个“条目”:

{"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":
[]
}
}

我只关心人员部分中的条目。基本上我需要读取并遍历条目(包含 ID、名称、年龄值)并将它们添加到集合或类中。 (之后我正在填充一个列表框。)

感谢任何指点。

最佳答案

我能够使用以下代码反序列化您的 JSON 字符串。这已经在 .NET 4 控制台应用程序中进行了测试,希望也能在 WP 7 中运行。

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(PersonCollection));

string json = "{\"lastUpdated\":\"16:12\",\"filterOut\":[],\"people\": [{\"ID\":\"a\",\"Name\":\"b\",\"Age\":\"c\"},{\"ID\":\"d\",\"Name\":\"e\",\"Age\":\"f\"},{\"ID\":\"x\",\"Name\":\"y\",\"Age\":\"z\"}], \"serviceDisruptions\": { \"infoMessages\": [\"blah blah text\"], \"importantMessages\": [], \"criticalMessages\": [] } }";

using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var people = (PersonCollection)serializer.ReadObject(stream);

foreach(var person in people.People)
{
Console.WriteLine("ID: {0}, Name: {1}, Age: {2}", person.ID, person.Name, person.Age);
}
}

使用以下数据类:

[DataContract]
public class PersonCollection
{
[DataMember(Name = "people")]
public IEnumerable<Person> People { get; set; }
}

[DataContract]
public class Person
{
[DataMember]
public string ID { get; set; }

[DataMember]
public string Name { get; set; }

[DataMember]
public string Age { get; set; }
}

关于c# - 在 WP7 中反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8201971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com