JSON is a popular way to represent and transfer data. Creating JSON with JSON.simple
(a Java library from Google) is very easy. JSON.simple also performs very well compared to other Java JSON libraries when parsing a variety of file sizes (see results of performance tests here).
Below is a simple example of building a JSON object using JSON.simple, and printing it. All of the keys in this example are strings, but numbers and more complex JSON structures like arrays can easily be added as values. Examples of using an integer as well as an array of strings is shown below:
package com.bigdatums.json;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonExamples {
public static void JsonSimpleExample(){
//add key value pairs to Json
JSONObject obj = new JSONObject();
obj.put("first_name", "Beyonce");
obj.put("last_name", "Knowles");
obj.put("birth_date", "1981-09-04");
obj.put("records_sold", 200000000);
//add array to Json
JSONArray list = new JSONArray();
list.add("Dangerously in Love");
list.add("B'Day");
list.add("I Am... Sasha Fierce");
list.add("4");
list.add("Beyonce");
obj.put("albums", list);
System.out.println(obj.toJSONString());
}
public static void main(String[] args){
JsonSimpleExample();
}
}
//output
// {"albums":["Dangerously in Love","B'Day","I Am... Sasha Fierce","4","Beyonce"],"birth_date":"1981-09-04","last_name":"Knowles","first_name":"Beyonce","records_sold":200000000}