【问题标题】:Parsing a json tree with gson用 gson 解析 json 树
【发布时间】:2016-12-19 13:28:15
【问题描述】:

我已将 GSON 作为 Java 中的 JSON 解析器,但密钥并不总是相同。 例如。我有以下 JSON:

  {
       "message":"....", 
         "categories_sorted": [
            {
              "550e8400-e29b-41d4-a716-446655440000": [
                {
                  "550e8400-e29b-41d4-a716-446655443333": [
                     {
                      "550e8400-e29b-41d4-a716-446655448964": []
                     }
                  ]
                },
                {
                  "550e8400-e29b-41d4-a716-446655443334": []
                }
              ]
            },
            {
              "550e8400-e29b-41d4-a716-446655440023": [
                {
                  "550e8400-e29b-41d4-a716-446655442344": []
                }
              ]
            }
          ]
        }

我需要解析这棵树“categories_sorted”。我的 Java POJO 对象:

public class CategoryPOJO {

    @SerializedName("message")
    @Expose
    private String message;

    @SerializedName("categories_sorted")
    @Expose
    private JsonArray sortedCategoryItems;

.......
Getters and setters
}

【问题讨论】:

标签: java android json gson


【解决方案1】:

您必须为此 ReferenceLink 执行 GSON Deserialiser 方法。例如,您必须像这样自定义:

@Override
public User deserialize(JsonElement json, Type type,
                        JsonDeserializationContext context) throws JsonParseException {

        return new CategoryPOJO(
            json.getAsJsonPrimitive().getAsInt(),
            json.getAsString(),
            json.getAsInt(),
            (CategoryPOJO)context.deserialize(json.getAsJsonPrimitive(),
            CategoryPOJO.class));
}

【讨论】:

    【解决方案2】:

    查看 jsonschema2pojo.org 资源以获取 POJO 类(选择 GSON 和 JSON 选项)

    【讨论】:

    • 我以前看过这个资源。但它不适合我,因为我的钥匙是动态的
    猜你喜欢
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 2011-02-12
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多