【问题标题】:GSON get string from complex jsonGSON 从复杂的 json 中获取字符串
【发布时间】:2015-04-07 16:14:00
【问题描述】:

我正在尝试从此链接解析 JSON:https://api.guildwars2.com/v2/items/56,一切都很好,直到我遇到这条线:"infix_upgrade":{"attributes":[{"attribute":"Power","modifier":4},{"attribute":"Precision","modifier":3}]} ...

如果我没有弄错:infix_upgrade在他里面有 1 个元素 attributesattributes 有 2 个元素,其中还有 2 个元素。这是二维数组吗?

我已经尝试过(代码太长,无法发布):

JsonObject _detailsObject = _rootObject.get("details").getAsJsonObject();
JsonObject infix_upgradeObject = _detailsObject.get("infix_upgrade").getAsJsonObject();
JsonElement _infix_upgrade_attributesElement = infix_upgradeObject.get("attributes");
JsonArray _infix_upgrade_attributesJsonArray = _infix_upgrade_attributesElement.getAsJsonArray();

问题是我不知道接下来要做什么,还尝试像这样继续将JsonArray转换为字符串数组:

Type _listType = new TypeToken<List<String>>() {}.getType();
List<String> _details_infusion_slotsStringArray = new Gson().fromJson(_infix_upgrade_attributesJsonArray, _listType);

但我得到了java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT,我猜这来自属性......

【问题讨论】:

    标签: java json jsp jakarta-ee gson


    【解决方案1】:

    使用适当的格式(例如JSONLint,检查 JSON 数据是否有效并进行格式设置,这使得结构比 GW 链接给出的更清晰),attributes 看起来实际上是这样的:

    "attributes": [
                    {
                        "attribute": "Power",
                        "modifier": 4
                    },
                    {
                        "attribute": "Precision",
                        "modifier": 3
                    }
                ]
    

    所以它是一个 JsonObject 数组,每个对象都是两个键值对。这就是解析器抛出错误的原因,因为您要求此数组仅包含 String ,但事实并非如此。

    所以实际的类型是:

    Type _listType = new TypeToken<List<JsonObject>>(){}.getType();
    

    问题是我不知道下一步该做什么

    等一下。您使用的是 Gson,而 Java 是一种 OO 语言,所以我建议您创建类。

    这对您之后获取数据和解析会更容易,因为您只需向解析器提供 JSON 数据表示的实际类的类(一些边缘情况可以通过编写自定义序列化程序来处理/解串器)。

    数据也比这一堆JsonObject/JsonArray/etc的类型好。

    这会给你一个很好的起点:

    class Equipment {
        private String name;
        private String description;
        ...
        @SerializedName("game_types")
        private List<String> gameTypes;
        ...
        private Details details;
        ...
    }
    class Details {
        ...
        @SerializedName("infix_upgrade")
        private InfixUpgrade infixUpgrade;
        ...
    }
    class InfixUpgrade {
        private List<Attribute> attributes; 
        ...
    }
    class Attribute {
        private String attribute;
        private int modifier;
        ...
    }
    

    然后将类型提供给解析器:

    Equipment equipment = new Gson().fromJson(jsonString, Equipment.class);
    

    希望对您有所帮助! :)

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多