【问题标题】:Gson to parse a recursive json structureGson 解析递归 json 结构
【发布时间】:2016-04-22 19:33:06
【问题描述】:

我正在使用 gson 从 json 字符串构建 Java 对象。 json 结构构建了一个“查询”,其中可以包含

a) 规则,由条件(AND 或 OR)组合

b) 一个或多个查询,由一个条件(AND 或 OR)组合

(a) 很简单,但是a 怎么实现(b)?

这里是一个 json 示例:

{
  "condition": "AND",
  "rules": [
    {
      "id": "amount",
      "field": "amount",
      "type": "double",
      "input": "text",
      "operator": "greater",
      "value": "80"
    },
    {
      "condition": "OR",
      "rules": [
        {
          "id": "text",
          "field": "text",
          "type": "string",
          "input": "text",
          "operator": "contains",
          "value": "rewe"
        },
        {
          "id": "text",
          "field": "text",
          "type": "string",
          "input": "text",
          "operator": "contains",
          "value": "aldi"
        }
      ]
    }
  ]
}

这是我的java类,代表json:

public class QueryBuilder {
    public String condition;
    private List<Rule> rules;
    private List<QueryBuilder> children;  // <-- should I do it like this?

    public static QueryBuilder buildFromJson(String json) {
//      Gson g = new Gson();
        Gson g = new GsonBuilder()
                //.registerTypeAdapter(Rule.class, new JsonCustomSerializer ())
                .create(); 

        return g.fromJson(json, QueryBuilder.class);
    }

    public String toJson() {
        Gson g = new Gson();
        return g.toJson(this);
    }

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public List<Rule> getRules() {
        return rules;
    }

    public void setRules(List<Rule> rules) {
        this.rules = rules;
    }



    public List<QueryBuilder> getChildren() {
        return children;
    }

    public void setChildren(List<QueryBuilder> children) {
        this.children = children;
    }

}

【问题讨论】:

    标签: json recursion gson


    【解决方案1】:

    使用这种 JSON 类型的有效负载,您将无法让 Gson 将其直接映射到某些类层次结构。您的评论行是正确的:您需要一个自定义转换器。使用新的TypeAdapter。在那里,您需要检测您是在阅读条件/规则还是查询。好消息是字段名称集不同,因此您只需读取第一个字段,然后分支读取完整的 RuleQuery 或您检测到的任何内容。

    看看JsonReader类,特别是peek方法。

    另外,请记住,您可以将解析委托给其他 TypeAdapter。这就是您要求的 recursion 部分。从Gson 对象,您可以为任何对象请求TypeAdapter。参见方法getAdapter。例如,您可以将它与 Rule 类一起使用。

    没有单一的解决方案。您可以编写所有的解析并进行所有的递归,您可以使用委托等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2011-05-05
      相关资源
      最近更新 更多