[英]Append a json object to another json object java
I have a two json objects我有两个 json 对象
JSONObject org_query = new JSONObject("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");
JSONObject query_form = new JSONObject("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");
I want to append the second object to first one inside the key must
and form a new JSON object.我想将第二个对象附加到 key must
第一个对象并形成一个新的 JSON 对象。
Required Output:所需输出:
{"query":{"bool":{"must_not":[],"should":[],"must":[{"match_phrase": {"Sales Channel": "Online"}}]}}}
I tried this,我试过这个,
org_query["query"]["bool"]["must"].append(query_form);
But shows error.但显示错误。
array type expected found org.json.jsonarray java
How to make it如何制作
在这种情况下,您可以执行以下操作:
org_query = org_query.put("query", org_query.getJSONObject("query").put("bool", org_query.getJSONObject("query").getJSONObject("bool").append("must", query_form)));
Not really sure which API you're using but a quick search on Google yielded this result:不确定您使用的是哪个 API,但在 Google 上快速搜索产生了以下结果:
The .append
method is for adding values into an array. .append
方法用于将值添加到数组中。
Try using .put
method.尝试使用.put
方法。 This is for adding values to a property by key.这是用于通过键向属性添加值。
Reference: https://docs.oracle.com/middleware/maf242/mobile/api-ref/oracle/adfmf/json/JSONObject.html参考: https : //docs.oracle.com/middleware/maf242/mobile/api-ref/oracle/adfmf/json/JSONObject.html
For more examples, see this other answer: https://stackoverflow.com/a/30006004/7119882有关更多示例,请参阅其他答案: https : //stackoverflow.com/a/30006004/7119882
You can use small json library您可以使用小型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.