问题描述
我正在使用 Json.Net 来解析一个数组.我要做的是将名称/值对从数组中提取出来,并在解析 JObject 时将它们分配给特定的变量.
I'm working with Json.Net to parse an array. What I'm trying to do is to pull the name/value pairs out of the array and assign them to specific variables while parsing the JObject.
这是我在数组中得到的:
Here's what I've got in the array:
[
{
"General": "At this time we do not have any frequent support requests."
},
{
"Support": "For support inquires, please see our support page."
}
]
这就是我在 C# 中得到的:
And here's what I've got in the C#:
WebRequest objRequest = HttpWebRequest.Create(dest);
WebResponse objResponse = objRequest.GetResponse();
using (StreamReader reader = new StreamReader(objResponse.GetResponseStream()))
{
string json = reader.ReadToEnd();
JArray a = JArray.Parse(json);
//Here's where I'm stumped
}
我对 JSON 和 Json.Net 还很陌生,所以它可能是其他人的基本解决方案.我基本上只需要在 foreach 循环中分配名称/值对,以便我可以在前端输出数据.有没有人这样做过?
I'm fairly new to JSON and Json.Net, so it might be a basic solution for someone else. I basically just need to assign the name/value pairs in a foreach loop so that I can output the data on the front-end. Has anyone done this before?
推荐答案
你可以像这样获取数据值:
You can get at the data values like this:
string json = @"
[
{ ""General"" : ""At this time we do not have any frequent support requests."" },
{ ""Support"" : ""For support inquires, please see our support page."" }
]";
JArray a = JArray.Parse(json);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + " -- " + value);
}
}
小提琴:https://dotnetfiddle.net/uox4Vt
这篇关于使用 Json.Net 解析 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!