json - 需要帮助来反序列化嵌套的 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
}
}
}
}
提前致谢
解决方案
这在 .NET Core 3.1 上非常适合我。
要测试它:
- 在 Visual Studio 2019 中,在 .NET Core 3.1 中创建一个 winform。确保它具有 Newtonsoft.JSON 的 NuGet 包。
- 添加一个名为 的按钮
btnJsonConvTest
和一个名为 的文本框txtJSONinput
。 - 向项目中添加一个新的类文件 - 名称无关紧要。从文件中删除标准内容。
- 选择并复制您的 JSON。在 Visual Studio 中,单击编辑 > 选择性粘贴 > 将 JSON 粘贴为类。这将创建您在下面看到的类结构。
- 从下面添加代码位。请注意,我给我的班级起了名字
JSONTestObject
。 - 运行程序,将 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 字符串,从而证明序列化和反序列化方法都正确地将数据移入和移出类属性。
推荐阅读
- javascript - vanilla js 'keyup' 可以工作,但不能在表单元素上'submit' 事件监听器
- c# - 如何将二维数组设置为单元测试的参数
- c++ - 是否有任何可移植的方法来确保在不使用 c++11 填充字节的情况下定义结构?
- python - 更改用户名后无法在 OS Catalina 上安装 anaconda
- domain-driven-design - DDD - 有界上下文共享/通信
- python - pandas:如果列大于 x,如何获得选择两列的最大值,否则选择平均值?
- ruby-on-rails - Rails 5.2 到 6.0 的迁移命名空间升级问题:未初始化的常量错误
- sed - 如何在 .css 文件中查找一行,然后更改以下括号之间的相关配置
- coq - coqIDE 未正确连接项目中的文件且未编译
- python - 掷骰子并定义 dmg_to_enemy