Paul Steven
Paul Steven

Reputation: 93

Append a json object to another json object java

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

Upvotes: 0

Views: 4880

Answers (3)

Anton Straka
Anton Straka

Reputation: 139

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();

Upvotes: 0

Nuno
Nuno

Reputation: 131

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)));

Upvotes: 1

narduw
narduw

Reputation: 65

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

Upvotes: 0

Related Questions