Skip to content

Instantly share code, notes, and snippets.

@twosouth
Last active June 28, 2018 17:01
Show Gist options
  • Save twosouth/c9da7e9d2bb1825dff43d1b03659cbc8 to your computer and use it in GitHub Desktop.
Save twosouth/c9da7e9d2bb1825dff43d1b03659cbc8 to your computer and use it in GitHub Desktop.
JSON Object with JSON Array containing JSON Objects that also contain a JSON Srray
package mcp.json.sample;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class MCPSimpleJSON_3 {
public static void main(String[] args) {
MCPSimpleJSON_3 msj = new MCPSimpleJSON_3();
System.out.println(msj.getJson());
}
@SuppressWarnings("unchecked")
public String getJson() {
// get the JSON api here: https://github.com/fangyidong/json-simple
// create this JSON block with the java below
// {
// "root": [{
// "firstName": "Scott",
// "lastName": "Salisbury",
// "zipCode": "37067",
// "cars": [{
// "car1": "2004 Toyota 4Runner"
// }, {
// "car2": "2018 Audi A7"
// }],
// "address2": "Apt B",
// "city": "Franklin",
// "address1": "10 Main St",
// "state": "TN"
// }, {
// "firstName": "John",
// "lastName": "Richards",
// "zipCode": "37067",
// "cars": [{
// "car1": "1965 Ford Mustang"
// }],
// "address2": "",
// "city": "Franklin",
// "address1": "105 Spark Lane",
// "state": "TN"
// }]
// }
JSONObject joTop = new JSONObject(); // will be the root node (see below)
JSONArray ja = new JSONArray(); // the JSONArray of the root node
JSONObject jo = new JSONObject(); // working JSONObject
jo.put("firstName", "Scott");
jo.put("lastName", "Salisbury");
jo.put("address1", "10 Main St");
jo.put("address2", "Apt B");
jo.put("city", "Franklin");
jo.put("state", "TN");
jo.put("zipCode", "37067");
JSONArray jaCars = new JSONArray();
JSONObject joCar = new JSONObject();
joCar.put("car1", "2004 Toyota 4Runner");
jaCars.add(joCar);
joCar = new JSONObject();
joCar.put("car2", "2018 Audi A7");
jaCars.add(joCar);
jo.put("cars", jaCars);
ja.add(jo); // add to JSONArray
jo = new JSONObject(); // same working JSONObject re-instantiated
jo.put("firstName", "John");
jo.put("lastName", "Richards");
jo.put("address1", "105 Spark Lane");
jo.put("address2", "");
jo.put("city", "Franklin");
jo.put("state", "TN");
jo.put("zipCode", "37067");
jaCars = new JSONArray();
joCar = new JSONObject();
joCar.put("car1", "1965 Ford Mustang");
jaCars.add(joCar);
jo.put("cars", jaCars);
ja.add(jo); // add to JSONArray
joTop.put("root", ja); // root node
return joTop.toString(); // return the created JSONObject as a string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment