Skip to content

Instantly share code, notes, and snippets.

@twosouth
Last active June 28, 2018 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twosouth/d97a5ce82d919d525f9641c4ce04c58c to your computer and use it in GitHub Desktop.
Save twosouth/d97a5ce82d919d525f9641c4ce04c58c to your computer and use it in GitHub Desktop.
Simple example of creating a JSON Array containing JSON objects
package mcp.json.sample;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class MCPSimpleJSON_2 {
public static void main(String[] args) {
MCPSimpleJSON_2 msj = new MCPSimpleJSON_2();
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",
// "address2": "Apt B",
// "city": "Franklin",
// "address1": "10 Main St",
// "state": "TN"
// }, {
// "firstName": "John",
// "lastName": "Richards",
// "zipCode": "37067",
// "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");
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");
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