如何使用 C# 中的 Newtonsoft json 将 JSON 反序列化为 .NET 对象并从数组中仅选择一个值?
csharpserver side programmingprogramming
WebClient 类提供了向由 URI 标识的任何本地、内联网或 Internet 资源发送数据或从其接收数据的常用方法。
WebClient 类使用 WebRequest 类提供对资源的访问。 WebClient 实例可以使用任何使用 WebRequest.RegisterPrefix 方法注册的 WebRequest 后代访问数据。
DownloadString 从资源下载字符串并返回字符串。
如果您的请求需要可选标头,则必须将标头添加到 Headers 集合中
示例
在下面的示例中,我们调用 url"https://jsonplaceholder.typicode.com/posts"
然后将示例反序列化为 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