Gson

https://github.com/google/gson
https://sites.google.com/site/gson/
http://www.simplecodestuffs.com/angularjs-interacting-with-java-servlet-using-json/
import com.google.gson.Gson;
import com.model.PersonData;
public class AngularJsServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public AngularJsServlet() {
                super();
        }

        protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
                PersonData personData = new PersonData();
                personData.setFirstName("Mohaideen");
                personData.setLastName("Jamil");

                String json = new Gson().toJson(personData);
                response.setContentType("application/json");
                response.getWriter().write(json);
        }
}
Example 2 
Java Reflection API, JSON2Java. 
https://www.journaldev.com/1789/java-reflection-example-tutorial

 <dependencies>
    <!--  Gson dependency -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.2.4</version>
    </dependency>
</dependencies>
--. JSON 2 List、Map、Array
----------
{
  "empID": 100,
  "name": "David",
  "permanent": false,
  "address": {
    "street": "BTM 1st Stage",
    "city": "Bangalore",
    "zipcode": 560100
  },
  "phoneNumbers": [
    123456,
    987654
  ],
  "role": "Manager",
  "cities": [
    "Los Angeles",
    "New York"
  ],
  "properties": {
    "age": "28 years",
    "salary": "1000 Rs"
  }
}
--------

Employee.java
package com.journaldev.json.model;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.google.gson.annotations.SerializedName;
public class Employee {
    @SerializedName("empID")
    private int id;
    private String name;
    private boolean permanent;
    private Address address;
    private long[] phoneNumbers;
    private String role;
    private List<String> cities;
    private Map<String, String> properties;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public boolean isPermanent() {
        return permanent;
    }
    public void setPermanent(boolean permanent) {
        this.permanent = permanent;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public long[] getPhoneNumbers() {
        return phoneNumbers;
    }
    public void setPhoneNumbers(long[] phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("***** Employee Details *****n");
        sb.append("ID="+getId()+"n");
        sb.append("Name="+getName()+"n");
        sb.append("Permanent="+isPermanent()+"n");
        sb.append("Role="+getRole()+"n");
        sb.append("Phone Numbers="+Arrays.toString(getPhoneNumbers())+"n");
        sb.append("Address="+getAddress()+"n");
        sb.append("Cities="+Arrays.toString(getCities().toArray())+"n");
        sb.append("Properties="+getProperties()+"n");
        sb.append("*****************************");
        return sb.toString();
    }
    public List<String> getCities() {
        return cities;
    }
    public void setCities(List<String> cities) {
        this.cities = cities;
    }
    public Map<String, String> getProperties() {
        return properties;
    }
    public void setProperties(Map<String, String> properties) {
        this.properties = properties;
    }

----
----Address.java
package com.journaldev.json.model;
public class Address {
    private String street;
    private String city;
    private int zipcode;
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getZipcode() {
        return zipcode;
    }
    public void setZipcode(int zipcode) {
        this.zipcode = zipcode;
    }
    @Override
    public String toString(){
        return getStreet() + ", "+getCity()+", "+getZipcode();
    }
}
-- Java object 2 JSON
----EmployeeGsonExample.java
package com.journaldev.json.gson;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.journaldev.json.model.Address;
import com.journaldev.json.model.Employee;
public class EmployeeGsonExample {
    public static void main(String[] args) throws IOException {
        Employee emp = createEmployee();
        // Get Gson object
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        // read JSON file data as String
        String fileData = new String(Files.readAllBytes(Paths
                .get("employee.txt")));
        // parse json string to object
        Employee emp1 = gson.fromJson(fileData, Employee.class);
        // print object data
        System.out.println("nnEmployee Objectnn" + emp1);
        // create JSON String from Object
        String jsonEmp = gson.toJson(emp);
        System.out.print(jsonEmp);
    }
    public static Employee createEmployee() {
        Employee emp = new Employee();
        emp.setId(100);
        emp.setName("David");
        emp.setPermanent(false);
        emp.setPhoneNumbers(new long[] { 123456, 987654 });
        emp.setRole("Manager");
        Address add = new Address();
        add.setCity("Bangalore");
        add.setStreet("BTM 1st Stage");
        add.setZipcode(560100);
        emp.setAddress(add);
        List<String> cities = new ArrayList<String>();
        cities.add("Los Angeles");
        cities.add("New York");
        emp.setCities(cities);
        Map<String, String> props = new HashMap<String, String>();
        props.put("salary", "1000 Rs");
        props.put("age", "28 years");
        emp.setProperties(props);
        return emp;
    }
}



Gson class has fromJson() and toJson(). The GsonBuilder class provides utility options for conversion, such as neat printing, field naming conversion, excluding fields, date formatting, and more.
   
Employee Object
***** Employee Details *****
ID=100
Name=David
Permanent=false
Role=Manager
Phone Numbers=[123456, 987654]
Address=BTM 1st Stage, Bangalore, 560100
Cities=[Los Angeles, New York]
Properties={age=28 years, salary=1000 Rs}
*****************************


---- For Memory Gson Streaming API。
 By Streaming API, JSON to Java Object
EmployeeGsonReader.java

package com.journaldev.json.gson;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.journaldev.json.model.Address;
import com.journaldev.json.model.Employee;
public class EmployeeGsonReader {
    public static void main(String[] args) throws IOException {
        InputStream is = new FileInputStream("employee.txt");
        InputStreamReader isr = new InputStreamReader(is);
        //create JsonReader object
        JsonReader reader = new JsonReader(isr);
        //create objects
        Employee emp = new Employee();
        Address add = new Address();
        emp.setAddress(add);
        List<Long> phoneNums = new ArrayList<Long>();
        emp.setCities(new ArrayList<String>());
        emp.setProperties(new HashMap<String, String>());
        String key = null;
        boolean insidePropertiesObj=false;
        key = parseJSON(reader, emp, phoneNums, key, insidePropertiesObj);
        long[] nums = new long[phoneNums.size()];
        int index = 0;
        for(Long l :phoneNums){
            nums[index++] = l;
        }
        emp.setPhoneNumbers(nums);
        reader.close();
        //print employee object
        System.out.println("Employee Objectnn"+emp);
    }
    private static String parseJSON(JsonReader reader, Employee emp,
            List<Long> phoneNums, String key, boolean insidePropertiesObj) throws IOException {
        //loop to read all tokens
                while(reader.hasNext()){
                    //get next token
                    JsonToken token = reader.peek();
                    switch(token){
                    case BEGIN_OBJECT:
                        reader.beginObject();
                        if("address".equals(key) || "properties".equals(key)){
                            while(reader.hasNext()){
                            parseJSON(reader, emp,phoneNums, key, insidePropertiesObj);
                            }
                            reader.endObject();
                        }
                        break;
                    case END_OBJECT:
                        reader.endObject();
                        if(insidePropertiesObj) insidePropertiesObj=false;
                        break;
                    case BEGIN_ARRAY:
                        reader.beginArray();
                        if("phoneNumbers".equals(key) || "cities".equals(key)){
                            while(reader.hasNext()){
                                parseJSON(reader, emp,phoneNums, key, insidePropertiesObj);
                                }
                            reader.endArray();
                        }
                        break;
                    case END_ARRAY:
                        reader.endArray();
                        break;
                    case NAME:
                        key = reader.nextName();
                        if("properties".equals(key)) insidePropertiesObj=true;
                        break;
                    case BOOLEAN:
                        if("permanent".equals(key)) emp.setPermanent(reader.nextBoolean());
                        else{
                            System.out.println("Unknown item found with key="+key);
                            //skip value to ignore it
                            reader.skipValue();
                        }
                        break;
                    case NUMBER:
                        if("empID".equals(key)) emp.setId(reader.nextInt());
                        else if("phoneNumbers".equals(key)) phoneNums.add(reader.nextLong());
                        else if("zipcode".equals(key)) emp.getAddress().setZipcode(reader.nextInt());
                        else {
                            System.out.println("Unknown item found with key="+key);
                            //skip value to ignore it
                            reader.skipValue();
                        }
                        break;
                    case STRING:
                        setStringValues(emp, key, reader.nextString(), insidePropertiesObj);
                        break;
                    case NULL:
                        System.out.println("Null value for key"+key);
                        reader.nextNull();
                        break;
                    case END_DOCUMENT:
                        System.out.println("End of Document Reached");
                        break;
                    default:
                        System.out.println("This part will never execute");
                        break;
                    }
                }
                return key;
    }
    private static void setStringValues(Employee emp, String key,
            String value, boolean insidePropertiesObj) {
        if("name".equals(key)) emp.setName(value);
        else if("role".equals(key)) emp.setRole(value);
        else if("cities".equals(key)) emp.getCities().add(value);
        else if ("street".equals(key)) emp.getAddress().setStreet(value);
        else if("city".equals(key)) emp.getAddress().setCity(value);
        else{
            //add to emp properties map
            if(insidePropertiesObj){
                emp.getProperties().put(key, value);
            }else{
                System.out.println("Unknown data found with key="+key+" value="+value);
            }
        }
    }
}
Since JSON is a recursive language, we also need to recursively call parsing methods on arrays and nested objects. JsonToken is a Java enumeration type returned by the next() method in JsonReader, and we can use it to perform conversion work with conditional logic or switch case statements. Based on the above code, you should be able to understand that this is not a simple implementation, if JSON is really complex, the code will become extremely difficult to maintain, so avoid using this method unless there is no other way out.
--- By Gson Streaming API  create Employee object.
EmployeeGsonWriter.java
    
package com.journaldev.json.gson;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Set;
import com.google.gson.stream.JsonWriter;
import com.journaldev.json.model.Employee;
public class EmployeeGsonWriter {
    public static void main(String[] args) throws IOException {
        Employee emp = EmployeeGsonExample.createEmployee();
        //writing on console, we can initialize with FileOutputStream to write to file
        OutputStreamWriter out = new OutputStreamWriter(System.out);
        JsonWriter writer = new JsonWriter(out);
        //set indentation for pretty print
        writer.setIndent("t");
        //start writing
        writer.beginObject(); //{
        writer.name("id").value(emp.getId()); // "id": 123
        writer.name("name").value(emp.getName()); // "name": "David"
        writer.name("permanent").value(emp.isPermanent()); // "permanent": false
        writer.name("address").beginObject(); // "address": {
            writer.name("street").value(emp.getAddress().getStreet()); // "street": "BTM 1st Stage"
            writer.name("city").value(emp.getAddress().getCity()); // "city": "Bangalore"
            writer.name("zipcode").value(emp.getAddress().getZipcode()); // "zipcode": 560100
            writer.endObject(); // }
        writer.name("phoneNumbers").beginArray(); // "phoneNumbers": [
            for(long num : emp.getPhoneNumbers()) writer.value(num); //123456,987654
            writer.endArray(); // ]
        writer.name("role").value(emp.getRole()); // "role": "Manager"
        writer.name("cities").beginArray(); // "cities": [
            for(String c : emp.getCities()) writer.value(c); //"Los Angeles","New York"
            writer.endArray(); // ]
        writer.name("properties").beginObject(); //"properties": {
            Set<String> keySet = emp.getProperties().keySet();
            for(String key : keySet) writer.name("key").value(emp.getProperties().get(key));//"age": "28 years","salary": "1000 Rs"
            writer.endObject(); // }
        writer.endObject(); // }
        writer.flush();
        //close writer
        writer.close();
    }
}
--- Java Object 2 JSON by streaming API, JsonWriter
reference:http://www.journaldev.com/?wpdmact=process&did=MzAuaG90bGluaw==
 http://www.journaldev.com/2315/java-json-example
 
 
JSON is widely used in web applications or as server response because it’s lightweight and more compact than XML. JSON objects are easy to read and write and most of the technologies provide support for JSON objects. That’s why JSON in Java web services are very popular.
JSR353 finally made into Java EE 7 and it’s the Java JSON processing API. jsonp is the reference implementation for Java JSON Processing API. We can use this in maven project by adding following dependency.
<dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <version>1.0.2</version> </dependency>If you are using GlassFish 4.0 then you can keep the scope as provided because it’s already included in the server.
JSON API provides two ways for JSON processing:
  1. Object Model API – It’s similar to DOM Parser and good for small objects.
  2. Streaming API – It’s similar to StaX Parser and good for large objects where you don’t want to keep whole object in memory.
Some important interfaces of Java JSON API are:
  1. javax.json.JsonReader: We can use this to read JSON object or an array to JsonObject. We can get JsonReader from Json class or JsonReaderFactory.
  2. javax.json.JsonWriter: We can use this to write JSON object to output stream.
  3. javax.json.stream.JsonParser: This works as a pull parser and provide streaming support for reading JSON objects.
  4. javax.json.stream.JsonGenerator: We can use this to write JSON object to output source in streaming way.
  5. javax.json.Json: This is the factory class for creating JSON processing objects. This class provides the most commonly used methods for creating these objects and their corresponding factories. The factory classes provide all the various ways to create these objects.
  6. javax.json.JsonObject: JsonObject represents an immutable JSON object value.
Let’s look into the usage of Java JSON API with simple program, we have a JSON object stored in a file employee.txt as;
{ "id":123, "name":"Pankaj Kumar", "permanent":true, "address":{ "street":"El Camino Real", "city":"San Jose", "zipcode":95014 }, "phoneNumbers":[9988664422, 1234567890], "role":"Developer" }We have java bean classes that represent above JSON format as:
package com.journaldev.model; import java.util.Arrays; public class Employee { private int id; private String name; private boolean permanent; private Address address; private long[] phoneNumbers; private String role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isPermanent() { return permanent; } public void setPermanent(boolean permanent) { this.permanent = permanent; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public long[] getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(long[] phoneNumbers) { this.phoneNumbers = phoneNumbers; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("***** Employee Details *****\n"); sb.append("ID="+getId()+"\n"); sb.append("Name="+getName()+"\n"); sb.append("Permanent="+isPermanent()+"\n"); sb.append("Role="+getRole()+"\n"); sb.append("Phone Numbers="+Arrays.toString(getPhoneNumbers())+"\n"); sb.append("Address="+getAddress()); sb.append("\n*****************************"); return sb.toString(); } }package com.journaldev.model; public class Address { private String street; private String city; private int zipcode; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getZipcode() { return zipcode; } public void setZipcode(int zipcode) { this.zipcode = zipcode; } @Override public String toString(){ return getStreet() + ", "+getCity()+", "+getZipcode(); } }I have overridden the toString() method to return human readable String representation that we will use in our JSON implementation classes.

Java JSON Read Example

package com.journaldev.json; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.json.JsonValue; import com.journaldev.model.Address; import com.journaldev.model.Employee; public class EmployeeJSONReader { public static final String JSON_FILE="employee.txt"; public static void main(String[] args) throws IOException { InputStream fis = new FileInputStream(JSON_FILE); //create JsonReader object JsonReader jsonReader = Json.createReader(fis); /** * We can create JsonReader from Factory also JsonReaderFactory factory = Json.createReaderFactory(null); jsonReader = factory.createReader(fis); */ //get JsonObject from JsonReader JsonObject jsonObject = jsonReader.readObject(); //we can close IO resource and JsonReader now jsonReader.close(); fis.close(); //Retrieve data from JsonObject and create Employee bean Employee emp = new Employee(); emp.setId(jsonObject.getInt("id")); emp.setName(jsonObject.getString("name")); emp.setPermanent(jsonObject.getBoolean("permanent")); emp.setRole(jsonObject.getString("role")); //reading arrays from json JsonArray jsonArray = jsonObject.getJsonArray("phoneNumbers"); long[] numbers = new long[jsonArray.size()]; int index = 0; for(JsonValue value : jsonArray){ numbers[index++] = Long.parseLong(value.toString()); } emp.setPhoneNumbers(numbers); //reading inner object from json object JsonObject innerJsonObject = jsonObject.getJsonObject("address"); Address address = new Address(); address.setStreet(innerJsonObject.getString("street")); address.setCity(innerJsonObject.getString("city")); address.setZipcode(innerJsonObject.getInt("zipcode")); emp.setAddress(address); //print employee bean information System.out.println(emp); } }The implementation is straight forward and feels similar as getting parameters from HashMap. JsonReaderFactory implements Factory Design Pattern. Once we execute above program, we get following output.
***** Employee Details ***** ID=123 Name=Pankaj Kumar Permanent=true Role=Developer Phone Numbers=[9988664422, 1234567890] Address=El Camino Real, San Jose, 95014 *****************************

Java JSON Write Example

package com.journaldev.json; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonWriter; import com.journaldev.model.Address; import com.journaldev.model.Employee; public class EmployeeJSONWriter { public static void main(String[] args) throws FileNotFoundException { Employee emp = createEmployee(); JsonObjectBuilder empBuilder = Json.createObjectBuilder(); JsonObjectBuilder addressBuilder = Json.createObjectBuilder(); JsonArrayBuilder phoneNumBuilder = Json.createArrayBuilder(); for (long phone : emp.getPhoneNumbers()) { phoneNumBuilder.add(phone); } addressBuilder.add("street", emp.getAddress().getStreet()) .add("city", emp.getAddress().getCity()) .add("zipcode", emp.getAddress().getZipcode()); empBuilder.add("id", emp.getId()) .add("name", emp.getName()) .add("permanent", emp.isPermanent()) .add("role", emp.getRole()); empBuilder.add("phoneNumbers", phoneNumBuilder); empBuilder.add("address", addressBuilder); JsonObject empJsonObject = empBuilder.build(); System.out.println("Employee JSON String\n"+empJsonObject); //write to file OutputStream os = new FileOutputStream("emp.txt"); JsonWriter jsonWriter = Json.createWriter(os); /** * We can get JsonWriter from JsonWriterFactory also JsonWriterFactory factory = Json.createWriterFactory(null); jsonWriter = factory.createWriter(os); */ jsonWriter.writeObject(empJsonObject); jsonWriter.close(); } public static Employee createEmployee() { Employee emp = new Employee(); emp.setId(100); emp.setName("David"); emp.setPermanent(false); emp.setPhoneNumbers(new long[] { 123456, 987654 }); emp.setRole("Manager"); Address add = new Address(); add.setCity("Bangalore"); add.setStreet("BTM 1st Stage"); add.setZipcode(560100); emp.setAddress(add); return emp; } }Once we run above application, we get following response:
Employee JSON String {"id":100,"name":"David","permanent":false,"role":"Manager","phoneNumbers":[123456,987654],"address":{"street":"BTM 1st Stage","city":"Bangalore","zipcode":560100}}JSON object is also getting saved in emp.txt file. JsonObjectBuilder implements builder pattern that makes it very easy to use.

Java JSON Parser Example

Java JsonParser is a pull parser and we read the next element with next() method that returns an Event object. javax.json.stream.JsonParser.Event is an Enum that makes it type-safe and easy to use. We can use in switch case to set our java bean properties.
package com.journaldev.json; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.json.Json; import javax.json.stream.JsonParser; import javax.json.stream.JsonParser.Event; import com.journaldev.model.Address; import com.journaldev.model.Employee; public class EmployeeJSONParser { public static final String FILE_NAME = "employee.txt"; public static void main(String[] args) throws IOException { InputStream fis = new FileInputStream(FILE_NAME); JsonParser jsonParser = Json.createParser(fis); /** * We can create JsonParser from JsonParserFactory also with below code * JsonParserFactory factory = Json.createParserFactory(null); * jsonParser = factory.createParser(fis); */ Employee emp = new Employee(); Address address = new Address(); String keyName = null; List<Long> phoneNums = new ArrayList<Long>(); while (jsonParser.hasNext()) { Event event = jsonParser.next(); switch (event) { case KEY_NAME: keyName = jsonParser.getString(); break; case VALUE_STRING: setStringValues(emp, address, keyName, jsonParser.getString()); break; case VALUE_NUMBER: setNumberValues(emp, address, keyName, jsonParser.getLong(), phoneNums); break; case VALUE_FALSE: setBooleanValues(emp, address, keyName, false); break; case VALUE_TRUE: setBooleanValues(emp, address, keyName, true); break; case VALUE_NULL: // don't set anything break; default: // we are not looking for other events } } emp.setAddress(address); long[] nums = new long[phoneNums.size()]; int index = 0; for(Long l :phoneNums){ nums[index++] = l; } emp.setPhoneNumbers(nums); System.out.println(emp); //close resources fis.close(); jsonParser.close(); } private static void setNumberValues(Employee emp, Address address, String keyName, long value, List<Long> phoneNums) { switch(keyName){ case "zipcode": address.setZipcode((int)value); break; case "id": emp.setId((int) value); break; case "phoneNumbers": phoneNums.add(value); break; default: System.out.println("Unknown element with key="+keyName); } } private static void setBooleanValues(Employee emp, Address address, String key, boolean value) { if("permanent".equals(key)){ emp.setPermanent(value); }else{ System.out.println("Unknown element with key="+key); } } private static void setStringValues(Employee emp, Address address, String key, String value) { switch(key){ case "name": emp.setName(value); break; case "role": emp.setRole(value); break; case "city": address.setCity(value); break; case "street": address.setStreet(value); break; default: System.out.println("Unknown Key="+key); } } }The major complexity comes when we need to write the logic to parse the data and sometimes it can get complex.
Since we are reading the same file as JsonReader, the output is same as EmployeeJsonReader program.

Java JsonGenerator Example

package com.journaldev.json; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.json.Json; import javax.json.stream.JsonGenerator; import com.journaldev.model.Employee; public class EmployeeJSONGenerator { public static void main(String[] args) throws IOException { OutputStream fos = new FileOutputStream("emp_stream.txt"); JsonGenerator jsonGenerator = Json.createGenerator(fos); /** * We can get JsonGenerator from Factory class also * JsonGeneratorFactory factory = Json.createGeneratorFactory(null); * jsonGenerator = factory.createGenerator(fos); */ Employee emp = EmployeeJSONWriter.createEmployee(); jsonGenerator.writeStartObject(); // { jsonGenerator.write("id", emp.getId()); // "id":123 jsonGenerator.write("name", emp.getName()); jsonGenerator.write("role", emp.getRole()); jsonGenerator.write("permanent", emp.isPermanent()); jsonGenerator.writeStartObject("address") //start of address object .write("street", emp.getAddress().getStreet()) .write("city",emp.getAddress().getCity()) .write("zipcode",emp.getAddress().getZipcode()) .writeEnd(); //end of address object jsonGenerator.writeStartArray("phoneNumbers"); //start of phone num array for(long num : emp.getPhoneNumbers()){ jsonGenerator.write(num); } jsonGenerator.writeEnd(); // end of phone num array jsonGenerator.writeEnd(); // } jsonGenerator.close(); } }JsonGenerator is very easy to use and provides good performance for large data.
That’s all for Java JSON Processing API. We learned about Java JSON Parser, Read and Write examples. You can download java project from below link and play around with it.
 JsonObject
 http://blog.csdn.net/qq651889264/article/details/22098733

1、JsonObject
Json string included { } must create a JsonObject
eg:
JsonObject spanObj=new JsonObject();
spanObj.addProperty("latitude_delta",0);
spanObj.addProperty("longitude_delta",0);
JsonObject regionObj=new JsonObject();
      regionObj.add("center", centerObj);
regionObj.add("span", spanObj);

JsonObject has 2 kinds of add(), addProperty(String Key, Value),Value will be any java base type, such as Boolean,Integer,String ...;
add(Key,Value), Value is JsonElement, like JsonArray, JsonNull, JsonObject, JsonPrimitive, which are subclasses of JsonElement.

2、JsonArray、JsonElement
Json string included "[ ]" need JsonArray or JsonElement
JsonArray add(JsonElement)
eg:
JsonArray businessesArray=new JsonArray();
businessesArray.add(businessObj);//businessObj is a JsonObject
to create JsonElement by toJsonTree() of Gson.
-----
Gson gson=new Gson();
List<String> cate1=new ArrayList<String>();
cate1.add("Local Flavor");
cate1.add("localflavor");

List<String> cate2=new ArrayList<String>();
cate2.add("Mass Media");
cate2.add("massmedia");

List<List<String>> cates=new ArrayList<List<String>>();
cates.add(cate1);cates.add(cate2);
JsonElement categoriesElement=gson.toJsonTree(cates);
--------
3、to JSON string

eg:
String gsonStr=gson.toJson(obj);
System.out.println(gsonStr);
System.out.println(obj);

4、Example
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class GsonAssembled {
public static void assembleGson(){
JsonObject obj=new JsonObject();
Gson gson=new Gson();
JsonObject businessObj=new JsonObject();
List<String> cate1=new ArrayList<String>();
cate1.add("Local Flavor");
cate1.add("localflavor");
List<String> cate2=new ArrayList<String>();
cate2.add("Mass Media");
cate2.add("massmedia");
List<List<String>> cates=new ArrayList<List<String>>();
cates.add(cate1);cates.add(cate2);
JsonElement categoriesElement=gson.toJsonTree(cates);
businessObj.add("categories", categoriesElement);
businessObj.addProperty("is_claimed",true );
businessObj.addProperty("is_closed",false );
businessObj.addProperty("name","Yelp" );
businessObj.addProperty("phone","4159083801" );
businessObj.addProperty("menu_date_updated",1317414369 );

JsonObject userBaseObj1=new JsonObject();
userBaseObj1.addProperty("name", "yuan");
userBaseObj1.addProperty("sex", "male");

JsonObject userBaseObj2=new JsonObject();
userBaseObj2.addProperty("name", "wang");
userBaseObj2.addProperty("sex", "female");
JsonArray userBaseArray=new JsonArray();
userBaseArray.add(userBaseObj1);
userBaseArray.add(userBaseObj2);
JsonObject userBaseObj=new JsonObject();
userBaseObj.add("user_base", userBaseArray);
businessObj.add("users", userBaseObj);
JsonObject centerObj=new JsonObject();
centerObj.addProperty("latitude",37.7861386 );
centerObj.addProperty("longitude",-122.4026213 );

JsonObject spanObj=new JsonObject();
spanObj.addProperty("latitude_delta",0);
spanObj.addProperty("longitude_delta",0);

JsonObject regionObj=new JsonObject();
regionObj.add("center", centerObj);
regionObj.add("span", spanObj);

JsonArray businessesArray=new JsonArray();
businessesArray.add(businessObj);
obj.add("businesses", businessesArray);
obj.add("region", regionObj);
obj.addProperty("total", 10651);

String gsonStr=gson.toJson(obj);
System.out.println(gsonStr);
System.out.println(obj);
}
 
 public static void main(String[] args) {
   GsonAssembled.assembleGson();
 }

}
/**
 *  example json string
 {
  "businesses": [
    {
      "categories": [
        ["Local Flavor","localflavor"],
        ["Mass Media","massmedia"]
      ],"is_claimed": true,"is_closed": false,
      "name": "Yelp","phone": "4159083801",
      "menu_date_updated": 1317414369,
      "users": {
        "user_base": [
          {"name": "yuan","sex": "male"},
          {"name": "wang","sex": "female"}
        ]
      }
    }
  ],
  "region": {
    "center": {"latitude": 37.7861386,"longitude": -122.4026213},
    "span": {"latitude_delta": 0,"longitude_delta": 0}
  },
  "total": 10651
}
**/

Example 3
          Gson gson=new Gson();
          Gson gson=new GsonBuilder().create();
User.java:

public class User {
         private String name;
         private int age;
         private String address;
         public String getName() {
                   return name;
         }
         public void setName(String name) {
                   this.name = name;
         }
         public int getAge() {
                   return age;
         }
         public void setAge(int age) {
                   this.age = age;
         }
         public String getAddress() {
                   return address;
         }
         public void setAddress(String address) {
                   this.address = address;
         }
         public User(String name, int age, String address) {
                   super();
                   this.name = name;
                   this.age = age;
                   this.address = address;
         }
         @Override
         public String toString() {
                   return "User [name=" + name + ", age=" + age + ", address=" + address
                                     + "]";
         }
}
------------------
                String jsonString="{'name':'tom','age':23,'address':'address0'}";
                
                   User u1=new User("name1", 25, "address1");
                   User u2=new User("name2", 23, "address2");
                
                   User []us={u1,u2};
                
                   List<User> users=new ArrayList<User>();
                   users.add(u1);
                   users.add(u2);              
                
                   Map<String,User> maps=new HashMap<String, User>();
                   maps.put("1001", u1);
                   maps.put("1002", u2);   

                   Gson g=new GsonBuilder().create();
                
                   //json 2 java
                   User u=g.fromJson(jsonString,User.class);
                   System.out.println(u);
       //output:User [name=tom, age=23, address=address0]

                   //java 2 json
                   jsonString=g.toJson(u);
                   System.out.println(jsonString);

      //output:{"name":"tom","age":23,"address":"address0"}
 
                   sonString=g.toJson(us);
                   System.out.println(jsonString);
       
                   us=null;
                   //json [] 2 java []
                   us=g.fromJson(jsonString, User[].class);
                   for(User uu:us){
                            System.out.println(uu);
                   }
                
                   //list2 json
                   jsonString=g.toJson(users);
                   System.out.println(jsonString);
                
                   users.clear();
                   //json [] 2 list
                   TypeToken<List<User>> typeToken=new TypeToken<List<User>>(){};
                   Type type=typeToken.getType();
                   //type is for List<User>
                   users=g.fromJson(jsonString,type);
                   for(User uu:users){
                            System.out.println(uu);
                   }
               
                   //map 2 json
                   jsonString=g.toJson(maps);
                   System.out.println(jsonString);
        
                   maps.clear();
                   // json [] 2 java Map
                   TypeToken<Map<String,User>> typeTokenMap=new TypeToken<Map<String,User>>(){};
                   Type typeMap=typeTokenMap.getType();
//If a generic collection is used, type is used to specify the specific type of the generic.
                   maps=g.fromJson(jsonString,typeMap);
                   for(Map.Entry<String, User> uu:maps.entrySet()){
                            System.out.println(uu.getValue());
                   }
From: http://www.itcast.cn/news/20151228/14540473622.shtml



评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE