【问题标题】:How to deserialize JSON string and parse it properly in C#?如何反序列化 JSON 字符串并在 C# 中正确解析它?
【发布时间】:2017-03-15 11:48:15
【问题描述】:

这个问题被问了很多次,但答案不符合我的需要。 我有一个示例 JSON 字符串,它是一个 JSON 数组。 我想解析它并能够选择要打印的值

在我的第一堂课中,我将 JSON 下载为字符串并使用 jsonConvert.DeserializeObject 对其进行解析

   using Newtonsoft.Json;

   namespace JSON_parser_2
   {
class Program
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        string downloadedString =     client.DownloadString("https://jsonplaceholder.typicode.com/posts");
        var result = JsonConvert.DeserializeObject<jsonStorage>(downloadedString);

“JsonStorage”是我在其中定义以下内容的类

    public string userId { get; set; }
    public string id { get; set; }
    public string title { get; set; }
    public string body { get; set; }

现在,在我的第一堂课中,我想打印整个解析的 JSON 或仅打印标题或正文,我该怎么做? 最终,我想打印来自给定链接的所有示例 cmets。

【问题讨论】:

  • 这里有问题吗,或者...?
  • 那么你已经成功解析了JSON??因为你的标题说如何反序列化 JSON 字符串并在 C# 中正确解析它?”
  • Parsing json objects的可能重复
  • 这听起来就像你只是想打印一个类,与解析 JSON 完全无关。
  • 问题是什么

标签: c# json json.net


【解决方案1】:

一种方法是使用Flurl.Http 库来检索json 一个强类型JsonStorage 对象的列表。通过将其转换为强 tped 对象列表,您可以控制打印哪些属性。只需下载Flurl.Http nuget 包即可使用以下代码:

using System;
using System.Collections.Generic;
using Flurl.Http;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var httpResponse = "https://jsonplaceholder.typicode.com/posts"
                            .GetJsonAsync<List<JsonStorage>>();

            httpResponse.Wait();

            var results = httpResponse.Result;

            foreach(var result in results)
            {
                Console.WriteLine($"title: {result.title}, body: {result.body}");
            }

            Console.ReadLine();
         }    
    }

    class JsonStorage
    {
        public string userId { get; set; }
        public string id { get; set; }
        public string title { get; set; }
        public string body { get; set; }
    }
}

【讨论】:

    【解决方案2】:
    public class jsonStorage
    {
        // your properties here
        ...
        ...
        // override the ToString
        public override string ToString()
        {
            return "userid=" + userId + Environment.NewLine +
                   "id=" + id + Environment.NewLine +
                   "title=" + title + Environment.NewLine +
                   "body=" + body;
        }
    }
    

    在main中,反序列化后,做ToString()

    var result = JsonConvert.DeserializeObject<jsonStorage>(downloadedString);
    Console.WriteLine(result.ToString());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      相关资源
      最近更新 更多