【问题标题】:How to access double nested Json field with Gson without creating additional classes如何在不创建其他类的情况下使用 Gson 访问双嵌套 Json 字段
【发布时间】:2021-07-23 14:55:00
【问题描述】:

所以我有下面的 JSON,我正在尝试用 Gson 库解析它。

{"id":"1",
"categoes":{
    "cars":"toyota",
    "airplanes":"airplane",
    "other_types":
        {"ships":{
                  "ice":"icebreakers"
                 }
        }
    }
}

我只想获取“ice”字段键和值,而不只创建一个 Java 类。

我该怎么做?

谢谢!

【问题讨论】:

  • 您已经上过哪些课程?你是如何尝试解决这个问题的?你遇到了什么错误?

标签: java json gson


【解决方案1】:

Gson 有一个名为 JsonObject 的预定义类,它允许您从 JSON 字符串中获取元素。这是一种(不是很漂亮)的方法:

Gson gson = new Gson();
JsonObject jobj = gson.fromJson(json, JsonObject.class);
        System.out.println(jobj.getAsJsonObject("categoes").getAsJsonObject("other_types").getAsJsonObject("ships").get("ice").getAsString());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 2019-03-12
    相关资源
    最近更新 更多