首页 > 解决方案 > 需要帮助来反序列化嵌套的 json 响应

问题描述

随着 web api 获得以下响应,希望帮助反序列化 vb.net 中的以下 json 响应。

 {
"data": {
    "getReport": {
        "report_date": "April 20, 2020",
        "report_date_iso": "2020-04-20",
        "links": {
            "__typename": "Links",
            "proportions_diagram": null
        },
        "results": {
            "shape_and_cutting_style": "Emerald Cut",               
            "data": {
                "shape": {
                    "shape_category": "F"                   
                },
                "girdle": null,
                "inscription_graphics": []
            }
        },
        "quota": {
            "remaining": 4971
        }
    }
}
 }  

提前致谢

标签: jsonvb.netjson.net

解决方案


这在 .NET Core 3.1 上非常适合我。

要测试它:

  1. 在 Visual Studio 2019 中,在 .NET Core 3.1 中创建一个 winform。确保它具有 Newtonsoft.JSON 的 NuGet 包。
  2. 添加一个名为 的按钮btnJsonConvTest和一个名为 的文本框txtJSONinput
  3. 向项目中添加一个新的类文件 - 名称无关紧要。从文件中删除标准内容。
  4. 选择并复制您的 JSON。在 Visual Studio 中,单击编辑 > 选择性粘贴 > 将 JSON 粘贴为类。这将创建您在下面看到的类结构。
  5. 从下面添加代码位。请注意,我给我的班级起了名字JSONTestObject
  6. 运行程序,将 JSON 测试字符串粘贴到文本框中,然后单击按钮。

代码:

using Newtonsoft.Json;

按钮点击事件:

private void btnJsonConvTest_Click(object sender, EventArgs e)
{
    JSONTestObject testobj = JsonConvert.DeserializeObject<JSONTestObject>(txtJSONinput.Text);
    String res = JsonConvert.SerializeObject(testobj);
    MessageBox.Show(res);
}

还有 VS 为我们创建的类:

public class JSONTestObject
{
    public Data data { get; set; }
}

public class Data
{
    public Getreport getReport { get; set; }
}

public class Getreport
{
    public string report_date { get; set; }
    public string report_date_iso { get; set; }
    public Links links { get; set; }
    public Results results { get; set; }
    public Quota quota { get; set; }
}

public class Links
{
    public string __typename { get; set; }
    public object proportions_diagram { get; set; }
}

public class Results
{
    public string shape_and_cutting_style { get; set; }
    public Data1 data { get; set; }
}

public class Data1
{
    public Shape shape { get; set; }
    public object girdle { get; set; }
    public object[] inscription_graphics { get; set; }
}

public class Shape
{
    public string shape_category { get; set; }
}

public class Quota
{
    public int remaining { get; set; }
}

当我测试它时,我得到了与进入它相同的 JSON 字符串,从而证明序列化和反序列化方法都正确地将数据移入和移出类属性。


推荐阅读