在JSONObject JAVA中获取序列/顺序的键

时间:2016-05-20 16:31:36

标签: java json

我正在尝试制作这样的JSON文档:

{
"query": {
  "bool":{
    "must":{
      "match": {
          "action": "HI"
      },
      "filter":{
        "range":{
          "epoch": {
              "gte" : "1454964688008"
          }
        }
      }
    }
  }
}

}

条件是匹配应始终位于过滤器JSONObject之前。

所以,从this thread看,我实现了这样的事情:

 public static String getQuery(Alert reqAlert) {


LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>>> main = new LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>>>();
        LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>> query = new LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>>();
        LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>> bool = new LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Serializable>>>();
        LinkedHashMap<String, LinkedHashMap<String, Serializable>> must = new LinkedHashMap<String, LinkedHashMap<String, Serializable>>();
        LinkedHashMap<String, Serializable> match = new LinkedHashMap<String, Serializable>();
        LinkedHashMap<String, Serializable> filter = new LinkedHashMap<String, Serializable>();
        LinkedHashMap<String, LinkedHashMap<String, String>> range = new LinkedHashMap<String, LinkedHashMap<String, String>>();
        LinkedHashMap<String, String> epoch = new LinkedHashMap<String, String>();
        epoch.put("gte", "1454964688008");
        range.put("epoch", epoch);
        filter.put("range", range);
        match.put("action", reqAlert.getQueryString());
        must.put("match", match);
        must.put("filter", filter);
        bool.put("must", must);
        query.put("bool", bool);
        main.put("query", query);


        JSONObject mainObject = new JSONObject(main);

        return mainObject.toString();
        }

但它始终打印

{"query":{"bool":{"must":{"filter":{"range":{"epoch":{"gte":"1454964688008"}}}},"match":{"action":"HI"}}}}

我该怎么办?

1 个答案:

答案 0 :(得分:0)

因此,如果有人也有相同的要求,那么最好的方法是使用来自以下maven依赖关系的JSONObject。

       <dependency>
            <groupId>org.codehaus.jettison</groupId>
            <artifactId>jettison</artifactId>
            <version>1.3.5</version>
        </dependency>

Jettison在内部使用LinkedHashMap。