programing

Json.Net을 사용하여 JSON 배열 구문 분석

kingscode 2021. 1. 18. 08:10
반응형

Json.Net을 사용하여 JSON 배열 구문 분석


배열을 구문 분석하기 위해 Json.Net과 협력하고 있습니다. 내가하려는 것은 배열에서 이름 / 값 쌍을 가져 와서 JObject를 구문 분석하는 동안 특정 변수에 할당하는 것입니다.

배열에있는 내용은 다음과 같습니다.

[
  {
    "General": "At this time we do not have any frequent support requests."
  },
  {
    "Support": "For support inquires, please see our support page."
  }
]

그리고 여기에 제가 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 루프에 이름 / 값 쌍을 할당하면 프런트 엔드에서 데이터를 출력 할 수 있습니다. 전에이 일을 한 적이 있습니까?


다음과 같은 데이터 값을 얻을 수 있습니다.

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


Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage 사용

그리고 전체 객체를 문자열로 변환 할 수 있습니다. filename.json은 문서 폴더에 있어야합니다.

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

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

        }
        Console.ReadLine();

ReferenceURL : https://stackoverflow.com/questions/15726197/parsing-a-json-array-using-json-net

반응형