C# 使用 Json.Net 解析 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15726197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:45:26  来源:igfitidea点击:

Parsing a JSON array using Json.Net

c#asp.netjsonjson.net

提问by johngeek

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.

我正在使用 Json.Net 来解析数组。我想要做的是从数组中提取名称/值对,并在解析 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."
  }
]

And here's what I've got in the C#:

这是我在 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

}

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?

我对 JSON 和 Json.Net 还很陌生,所以它可能是其他人的基本解决方案。我基本上只需要在 foreach 循环中分配名称/值对,以便我可以在前端输出数据。以前有人这样做过吗?

采纳答案by Brian Rogers

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);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

小提琴:https: //dotnetfiddle.net/uox4Vt

回答by SDAL

Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage

使用 Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage

And you can convert the entire object to a string, filename.json is expected to be located in documents folder.

您可以将整个对象转换为字符串,filename.json 应位于文档文件夹中。

        var text = File.ReadAllText("filename.json");
        var json = JsonValue.Parse(text);

        while (JsonValue.Null != null)
        {
            Console.WriteLine(json.ToString());

        }
        Console.ReadLine();