Zeeshan
Zeeshan

Reputation: 1655

how to make json in java

I am having problem putting jsonObject(s) in jsonArray.

here is JSON format:

     {
       "op": "add",
       "array": 
           [
            {
             "field": "fld",
             "value": "20"
            },
            {
             "field": "fldu",
             "value": "z"
            }
           ]
    }

I am trying with this code:

JSONObject jsonObj = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonObj .put("operation", "add");
jsonObj .put("array",jsonArray.put( jsonObj.put("field", "fld_name")));

but it gives an error. What am I doing wrong? Any ideas?

Upvotes: 0

Views: 94

Answers (1)

Jayyrus
Jayyrus

Reputation: 13051

JSONObject json = new JSONObject();
json.put("operation","add");

JSONArray array = new JSONArray();
JSONObject fields1 = new JSONObject();
fields1.put("field","fld");
fields1.put("value","20");
JSONObject fields2 = new JSONObject();
fields2.put("field","fldu");
fields2.put("value","z");

array.put(fields1);
array.put(fields2);

json.put("array",array);

Upvotes: 2

Related Questions