Programming

C #으로 JSON을 구문 분석하려면 어떻게해야합니까?

procodes 2020. 2. 20. 23:37
반응형

C #으로 JSON을 구문 분석하려면 어떻게해야합니까?


다음 코드가 있습니다.

var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);

입력 responsecontent이 JSON이지만 객체로 올바르게 구문 분석되지 않았습니다. 직렬화를 제대로 해제하려면 어떻게해야합니까?


Json.NET (Newtonsoft.Json NuGet 패키지)을 사용하지 않는다고 가정합니다 . 이 경우 시도해보십시오.

다음과 같은 기능이 있습니다.

  1. LINQ to JSON
  2. .NET 객체를 JSON으로 빠르게 변환하고 다시 되돌릴 수있는 JsonSerializer
  3. Json.NET은 디버깅 또는 표시를 위해 잘 형식화되고 들여 쓰기 된 JSON을 선택적으로 생성 할 수 있습니다.
  4. JsonIgnore 및 JsonProperty와 같은 속성을 클래스에 추가하여 클래스 직렬화 방법을 사용자 정의 할 수 있습니다.
  5. JSON과 XML 간 변환 기능
  6. .NET, Silverlight 및 Compact Framework와 같은 여러 플랫폼 지원

아래 예를 보십시오 . 이 예에서 JsonConvert클래스는 객체를 JSON으로 또는 JSON에서 변환하는 데 사용됩니다. 이를 위해 두 가지 정적 메소드가 있습니다. 그들은 있습니다 SerializeObject(Object obj)DeserializeObject<T>(String json):

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

여기에 답변 된 것처럼 -JSON을 C # 동적 객체로 직렬화 해제 하시겠습니까?

Json.NET을 사용하는 것은 매우 간단합니다.

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

또는 Newtonsoft.Json.Linq 사용 :

dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;

타사 라이브러리 사용 하지 않는 옵션은 다음과 같습니다 .

// For that you will need to add reference to System.Runtime.Serialization
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"), new System.Xml.XmlDictionaryReaderQuotas());

// For that you will need to add reference to System.Xml and System.Xml.Linq
var root = XElement.Load(jsonReader);
Console.WriteLine(root.XPathSelectElement("//Name").Value);
Console.WriteLine(root.XPathSelectElement("//Address/State").Value);

// For that you will need to add reference to System.Web.Helpers
dynamic json = System.Web.Helpers.Json.Decode(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }");
Console.WriteLine(json.Name);
Console.WriteLine(json.Address.State);

System.Web.Helpers.Json에 대한 자세한 정보는 링크를 참조하십시오 .

업데이트 : 요즘 가장 쉬운 방법 Web.HelpersNuGet 패키지 를 사용하는 것 입니다.


이전 Windows 버전에 신경 쓰지 않으면 Windows.Data.Json네임 스페이스 의 클래스를 사용할 수 있습니다 .

// minimum supported version: Win 8
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
Console.WriteLine(root["Name"].GetString());
Console.WriteLine(root["Address"].GetObject()["State"].GetString());

.NET 4를 사용할 수있는 경우 http://visitmix.com/writings/the-rise-of-json(archive.org)을 확인하십시오.

해당 사이트의 스 니펫은 다음과 같습니다.

WebClient webClient = new WebClient();
dynamic result = JsonValue.Parse(webClient.DownloadString("https://api.foursquare.com/v2/users/self?oauth_token=XXXXXXX"));
Console.WriteLine(result.response.user.firstName);

마지막 Console.WriteLine은 꽤 달콤합니다 ...


타사 라이브러리가 필요하지 않지만 System.Web.Extensions에 대한 참조 는 JavaScriptSerializer입니다. 이것은 3.5 이래로 새로운 기능은 아니지만 매우 알려지지 않은 내장 기능입니다.

using System.Web.Script.Serialization;

..

JavaScriptSerializer serializer = new JavaScriptSerializer();
objectString = serializer.Serialize(new MyObject());

그리고 다시

MyObject o = serializer.Deserialize<MyObject>(objectString)

DataContractJsonSerializer를 살펴볼 수도 있습니다.


System.Json이 지금 작동합니다 ...

너겟 설치 https://www.nuget.org/packages/System.Json

PM> Install-Package System.Json -Version 4.5.0

샘플 :

// PM>Install-Package System.Json -Version 4.5.0

using System;
using System.Json;

namespace NetCoreTestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Note that JSON keys are case sensitive, a is not same as A.

            // JSON Sample
            string jsonString = "{\"a\": 1,\"b\": \"string value\",\"c\":[{\"Value\": 1}, {\"Value\": 2,\"SubObject\":[{\"SubValue\":3}]}]}";

            // You can use the following line in a beautifier/JSON formatted for better view
            // {"a": 1,"b": "string value","c":[{"Value": 1}, {"Value": 2,"SubObject":[{"SubValue":3}]}]}

            /* Formatted jsonString for viewing purposes:
            {
               "a":1,
               "b":"string value",
               "c":[
                  {
                     "Value":1
                  },
                  {
                     "Value":2,
                     "SubObject":[
                        {
                           "SubValue":3
                        }
                     ]
                  }
               ]
            }
            */

            // Verify your JSON if you get any errors here
            JsonValue json = JsonValue.Parse(jsonString);

            // int test
            if (json.ContainsKey("a"))
            {
                int a = json["a"]; // type already set to int
                Console.WriteLine("json[\"a\"]" + " = " + a);
            }

            // string test
            if (json.ContainsKey("b"))
            {
                string b = json["b"];  // type already set to string
                Console.WriteLine("json[\"b\"]" + " = " + b);
            }

            // object array test
            if (json.ContainsKey("c") && json["c"].JsonType == JsonType.Array)
            {
                // foreach loop test
                foreach (JsonValue j in json["c"])
                {
                    Console.WriteLine("j[\"Value\"]" + " = " + j["Value"].ToString());
                }

                // multi level key test
                Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][0]["Value"].ToString());
                Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][1]["Value"].ToString());
                Console.WriteLine("json[\"c\"][1][\"SubObject\"][0][\"SubValue\"]" + " = " + json["c"][1]["SubObject"][0]["SubValue"].ToString());
            }

            Console.WriteLine();
            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }
    }
}

이 도구를 사용하여 json을 기반으로 클래스를 생성하십시오.

http://json2csharp.com/

그런 다음 클래스를 사용하여 json을 직렬화 해제하십시오. 예:

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}


string json = @"{
  'Email': 'james@example.com',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.Email);
// james@example.com

참조 : https://forums.asp.net/t/1992996.aspx?Nested+Json+Deserialization+to+C+object+and+using+that+that+object https://www.newtonsoft.com/json/help /html/DeserializeObject.htm


다음 코드를 시도하십시오.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
JArray array = new JArray();
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var objText = reader.ReadToEnd();

    JObject joResponse = JObject.Parse(objText);
    JObject result = (JObject)joResponse["result"];
    array = (JArray)result["Detail"];
    string statu = array[0]["dlrStat"].ToString();
}

msdn 사이트 의 다음 내용은 원하는 것에 대한 일부 기본 기능을 제공하는 데 도움 된다고 생각합니다. Windows 8에 지정되어 있습니다. 사이트에서 이러한 예제 중 하나가 아래에 나열되어 있습니다.

JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");

Windows.Data.JSON 네임 스페이스를 사용합니다 .


         string json = @"{
            'Name': 'Wide Web',
            'Url': 'www.wideweb.com.br'}";

        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        dynamic j = jsonSerializer.Deserialize<dynamic>(json);
        string name = j["Name"].ToString();
        string url = j["Url"].ToString();

내가 본 가장 좋은 대답은 @MD_Sayem_Ahmed라고 생각합니다.

귀하의 질문은 "Json을 C #으로 구문 분석하는 방법"이지만 Json을 디코딩하려는 것 같습니다. 그것을 해독하고 싶다면 Ahmed의 대답이 좋습니다.

ASP.NET Web Api에서이 작업을 수행하려는 경우 가장 쉬운 방법은 할당하려는 데이터를 보유하는 데이터 전송 개체를 만드는 것입니다.

public class MyDto{
    public string Name{get; set;}
    public string Value{get; set;}
}

Fiddler를 사용하는 경우 응용 프로그램 / json 헤더를 요청에 추가하기 만하면됩니다. 그런 다음 ASP.NET 웹 API에서 다음과 같이 사용합니다.

//controller method -- assuming you want to post and return data
public MyDto Post([FromBody] MyDto myDto){
   MyDto someDto = myDto;
   /*ASP.NET automatically converts the data for you into this object 
    if you post a json object as follows:
{
    "Name": "SomeName",
      "Value": "SomeValue"
}
*/
   //do some stuff
}

이것은 Web Api에서 일할 때 많은 도움이되었고 인생을 아주 쉽게 만들었습니다.


 using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(user)))
 {
    // Deserialization from JSON  
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UserListing))
    DataContractJsonSerializer(typeof(UserListing));
    UserListing response = (UserListing)deserializer.ReadObject(ms);

 }

 public class UserListing
 {
    public List<UserList> users { get; set; }      
 }

 public class UserList
 {
    public string FirstName { get; set; }       
    public string LastName { get; set; } 
 }

var result = controller.ActioName(objParams);
IDictionary<string, object> data = (IDictionary<string, object>)new System.Web.Routing.RouteValueDictionary(result.Data);
Assert.AreEqual("Table already exists.", data["Message"]);

참고 URL : https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c



반응형