如何在 c# 中使用 Newtonsoft JSON 將 JSON 反序列化為 .NET 物件,並且只從陣列中選取一個值?


WebClient 類提供了一些常見方法,用於將資料傳送到或接收自任何 URL 識別的本地、內聯網或網際網路資源。

WebClient 類使用 WebRequest 類提供對資源的訪問。WebClient 例項可以用任何已向 WebRequest.RegisterPrefix 方法註冊的 WebRequest 子類訪問資料。

DownloadString 從資源下載一個字串並返回一個字串。

如果您的請求需要一個可選請求頭,您必須將該請求頭新增到 Headers 集合中

示例

  • 在下面的示例中,我們正在呼叫 URL “https://jsonplaceholder.typicode.com/posts”

  • 然後將該示例反序列化為 User 陣列

  • 我們正在從 user 陣列中打印出第一個陣列值

示例

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

更新時間:2020 年 11 月 5 日

517 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始
廣告