[英]Append a json object to another json object java
我有兩個 json 對象
JSONObject org_query = new JSONObject("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");
JSONObject query_form = new JSONObject("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");
我想將第二個對象附加到 key must
第一個對象並形成一個新的 JSON 對象。
所需輸出:
{"query":{"bool":{"must_not":[],"should":[],"must":[{"match_phrase": {"Sales Channel": "Online"}}]}}}
我試過這個,
org_query["query"]["bool"]["must"].append(query_form);
但顯示錯誤。
array type expected found org.json.jsonarray java
如何制作
在這種情況下,您可以執行以下操作:
org_query = org_query.put("query", org_query.getJSONObject("query").put("bool", org_query.getJSONObject("query").getJSONObject("bool").append("must", query_form)));
不確定您使用的是哪個 API,但在 Google 上快速搜索產生了以下結果:
.append
方法用於將值添加到數組中。
嘗試使用.put
方法。 這是用於通過鍵向屬性添加值。
參考: https : //docs.oracle.com/middleware/maf242/mobile/api-ref/oracle/adfmf/json/JSONObject.html
有關更多示例,請參閱其他答案: https : //stackoverflow.com/a/30006004/7119882
您可以使用小型json庫
JsonValue org_query = JsonParser.parse("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");
JsonValue query_form = JsonParser.parse("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");
JsonValue must = org_query.findFirst(SPM.path("query", "bool", "must"));
must.asArray().add(query_form);
String result = org_query.toCompactString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.