1
我使用gson從json字符串構建Java對象。 JSON的結構建立了一個「詢問」是可包含任一Gson解析遞歸json結構
一個)規則,由條件組合(AND或OR)再次
b)一種礦石多個查詢,合併由條件(AND或OR) (一)很簡單,但一個工具(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;
}
}