programing

json을 C# 어레이로 변환하시겠습니까?

starjava 2023. 3. 18. 08:14
반응형

json을 C# 어레이로 변환하시겠습니까?

json을 포함하는 문자열을 C# 배열로 변환하는 방법을 아는 사람이 있습니까?webBrowser에서 텍스트/json을 읽어 문자열에 저장하는 기능이 있습니다.

string docText = webBrowser1.Document.Body.InnerText;

어떻게 해서든 json 문자열을 배열로 바꾸면 돼Json을 보고 있었어.NET은 어레이를 json으로 변경하고 싶지 않기 때문에 이것이 필요한지는 잘 모르겠습니다만, 그 반대입니다.도와줘서 고마워요!

문자열을 가져와 JavaScriptSerializer를 사용하여 네이티브 객체로 역직렬화하기만 하면 됩니다.예를 들어 다음과 같은 json이 있습니다.

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

예를 들어 다음과 같이 정의된 개인이라는 이름의 C# 클래스를 만들어야 합니다.

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

이것으로 JSON 문자열을 Person 배열로 역직렬화할 수 있습니다.

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

다음은 JavaScriptSerializer 설명서에 대한 링크입니다.

주의: 위의 코드는 테스트되지 않았지만 테스트된 것입니다.특별한 작업을 하고 있지 않는 한 Javascript Serializer를 사용하면 됩니다.

using Newtonsoft.Json;

패키지 콘솔에 이 클래스를 설치합니다.이 클래스는 모두 정상적으로 동작합니다.NET Versions(예: 프로젝트:DNX 4.5.1과 DNX CORE 5.0을 가지고 있으며 모든 것이 작동합니다.

먼저 JSON 역직렬화 전에 정상적으로 읽고 데이터를 저장할 클래스를 선언해야 합니다.이것이 제 클래스입니다.

public class ToDoItem
{
    public string text { get; set; }
    public string complete { get; set; }
    public string delete { get; set; }
    public string username { get; set; }
    public string user_password { get; set; }
    public string eventID { get; set; }
}

GET 요청으로 데이터를 요청하는 HttpContent 섹션은 다음과 같습니다.

HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);

네, Json.필요한 것은 인터넷입니다.기본적으로 Json 문자열을 다음과 같은 배열로 역직렬화하려고 합니다.objects.

를 참조해 주세요.

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

오래된 질문이지만 사용하는 경우 답변을 추가할 가치가 있습니다.NET Core 3.0 이후JSON의 시리얼화/디시리얼화는 프레임워크에 포함되어 있습니다(시스템).Text.Json)을 사용하면 서드파티 라이브러리를 더 이상 사용할 필요가 없습니다.다음은 @Icarus가 제시한 상위 답변을 바탕으로 한 예입니다.

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

다른 응답에서 다루지 않은 한 가지 상황은 JSON 객체에 포함된 항목의 유형을 모르는 경우입니다.그것은 내가 그것을 타이핑하지 않고 역동적으로 할 수 있어야 했기 때문에 나의 경우였다.

var objectWithFields =  js.Deserialize<dynamic[]>(json);

주의: 반드시 타입을 선택하는 것이 좋습니다만, 경우에 따라서는 불가능할 수 있기 때문에, 이 답변을 추가했습니다.

언급URL : https://stackoverflow.com/questions/9586585/convert-json-to-a-c-sharp-array

반응형