0

I have a two json objects

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.

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

Paul Steven
  • 93
  • 4
  • 13

3 Answers3

1

In this case you can do:

org_query = org_query.put("query", org_query.getJSONObject("query").put("bool", org_query.getJSONObject("query").getJSONObject("bool").append("must", query_form)));
Jagadesh
  • 2,104
  • 1
  • 16
  • 28
Nuno
  • 131
  • 6
0

Not really sure which API you're using but a quick search on Google yielded this result:

The .append method is for adding values into an array.

Try using .put method. 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

For more examples, see this other answer: https://stackoverflow.com/a/30006004/7119882

narduw
  • 40
  • 1
  • 5
  • Thanks... I found that... `org_query.getJSONObject("query").getJSONObject("bool").getJSONArray("must").put(query_form);` – Paul Steven Feb 14 '20 at 13:36
0

You can use small json library

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();
Anton Straka
  • 139
  • 2