Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 Newtonsoft json을 사용하여 JSON을 .NET 개체로 역직렬화하고 배열에서 하나의 값만 선택하는 방법은 무엇입니까?

<시간/>

WebClient 클래스는 URI로 식별되는 로컬, 인트라넷 또는 인터넷 리소스와 데이터를 주고받는 일반적인 방법을 제공합니다.

WebClient 클래스는 WebRequest 클래스를 사용하여 리소스에 대한 액세스를 제공합니다. WebClient 인스턴스는 WebRequest.RegisterPrefix 메소드로 등록된 모든 WebRequest 자손으로 데이터에 액세스할 수 있습니다.

DownloadString 리소스에서 문자열을 다운로드하고 문자열을 반환합니다.

요청에 선택적 헤더가 필요한 경우 헤더를 헤더 컬렉션에 추가해야 합니다.

  • 아래 예에서는 URL을 "https://jsonplaceholder.typicode.com/posts"

    라고 부릅니다.
  • 그런 다음 예제는 사용자 배열

    로 역직렬화됩니다.
  • 사용자 배열에서 첫 번째 배열 값을 인쇄하고 있습니다.

class Program{
   static void Main(string[] args){
      var client = new WebClient();
      var json = client.DownloadString("https://jsonplaceholder.typicode.com/posts");
      var userPosts = JsonConvert.DeserializeObject<User[]>(json);
      System.Console.WriteLine(userPosts[0].title);
      Console.ReadLine();
   }
}
public class User{
   public string userId { get; set; }
   public string id { get; set; }
   public string title { get; set; }
   public string body { get; set; }
}

출력

sunt aut facere repellat provident occaecati excepturi optio reprehenderit