Harry
Harry

Reputation: 548

JsonObject in Java

Original Question: Resolved

I'm producing Json from the controller using JsonObject/JsonArray:

    JSONObject headers = new JSONObject();
    headers.put("ID", "");
    headers.put("Organization Name", "");
    headers.put("Submission Date", "");
    headers.put("Status", "");

    JSONObject organizationsHJ = new JSONObject();
    organizationsHJ.put("headers", headers);

    array.add(organizationsHJ );

This produces JSON as: "headers":{"Status":"","Submission Date":"","Organization Name":"","ID":""}

Instead I need to get the output as:

"headers":[  "ID",  "Organization Name",  "Submission Date",  "Status"  ]

Is that possible? Please advise. Please note I can have the JSON as a javascript variable as well if that's easier?

EDIT:

I need one more simple change in the JSON output. Here is my code:

JSONObject notifications = new JSONObject();
notifications.put("id", "1");
notifications.put("description", "Notification 1");
notifications.put("createdTimestamp", "2015-05-12T18:15:28.237Z");
notifications.put("startTimestamp", "2015-05-25T18:30:28.237Z");
notifications.put("endTimestamp", "2015-06-13T12:30:30.237Z");
notifications.put("active", "true");

This generates JSON output as:

{"data":{"id":"1","createdTimestamp":"2015-05-12T18:15:28.237Z","description":"Notification 1","startTimestamp":"2015-05-25T18:30:28.237Z","active":"true","createdId":"251","endTimestamp":"2015-06-13T12:30:30.237Z"}}

Instead I want it to generate as:

{"data":["id":"1","createdTimestamp":"2015-05-12T18:15:28.237Z","description":"Notification 1","startTimestamp":"2015-05-25T18:30:28.237Z","active":"true","createdId":"251","endTimestamp":"2015-06-13T12:30:30.237Z"]}

Upvotes: 0

Views: 139

Answers (2)

Barmar
Barmar

Reputation: 782785

headers should be a JSONArray, not JSONObject. An object is a set of name-to-value mappings, an array is a linear collection.

JSONArray headers = new JSONObject();
headers.add("ID");
headers.add("Organization Name");
headers.add("Submission Date");
headers.add("Status");

JSONObject organizationsHJ = new JSONObject();
organizationsHJ.put("headers", headers);

array.add(organizationsHJ );

Upvotes: 2

Eric Hartford
Eric Hartford

Reputation: 18032

organizationsHJ.put("headers", headers.keySet());

Upvotes: 1

Related Questions