Handle JSON object Tag(s): Networking XML/RSS/JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is used primarily to transmit data between a server and web application, as an alternative to XML. JSON structures are easy to manipulate from Java. The required libraries are now included in the Java EE 7 specification.
Create a JSON object from a String
In this HowTo, we create a JSON object from a String. In a MAVEN project, add this dependency<dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <version>1.0.4</version> </dependency>
import java.io.StringReader; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; // https://jsonp.java.net/download.html public class Json1 { String jsonString = "{" + " \"firstName\": \"John\", \"lastName\": \"Smith\", \"age\": 25," + " \"address\" : { " + " \"streetAddress\": \"21 2nd Street\"," + " \"city\": \"New York\"," + " \"state\": \"NY\"," + " \"postalCode\": \"10021\"" + " }," + " \"phoneNumber\": [" + " { \"type\": \"home\", \"number\": \"212 555-1234\" }," + " { \"type\": \"fax\", \"number\": \"646 555-4567\" }" + " ]" + "}"; public static void main(String args[]) { Json1 x = new Json1(); x.doit(); } public void doit() { JsonReader reader = Json.createReader(new StringReader(jsonString)); JsonObject object = reader.readObject(); reader.close(); System.out.println(object.getString("firstName") + " " + object.getString("lastName")) ; System.out.println(object.getJsonObject("address").getString("city")) ; /* output : John Smith New York */ } }
Create a JSON object from a File
To use a file, replace the StringReader by a FileReader.Create a JSON object from code
Now, we want to create the JSON object from code.import javax.json.Json; import javax.json.JsonObject; public class Json2 { public static void main(String args[]) { Json2 x = new Json2(); x.doit(); } public void doit() { JsonObject object = Json.createObjectBuilder() .add("firstName", "John") .add("lastName", "Smith") .add("age", 25) .add("address", Json.createObjectBuilder() .add("streetAddress", "21 2nd Street") .add("city", "New York") .add("state", "NY") .add("postalCode", "10021")) .add("phoneNumber", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("number", "212 555-1234")) .add(Json.createObjectBuilder() .add("type", "fax") .add("number", "646 555-4567"))) .build(); System.out.println(object.getString("firstName") + " " + object.getString("lastName")) ; System.out.println(object.getJsonObject("address").getString("city")) ; } }
Create a JSON object from a REST service response
To call the REST service, we will use the HTTPClient module from Apache. In a MAVEN project, add these dependencies<dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <version>1.0.4</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version> </dependency>
The raw response looks like
{ "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit ...eveniet architecto" }
import java.io.InputStreamReader; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; public class Json3 { public static void main(String args[]) throws Exception { Json3 x = new Json3(); x.doit(); } public void doit() throws Exception { JsonReader reader = null; CloseableHttpClient client = HttpClientBuilder.create().build(); HttpHost target = new HttpHost("jsonplaceholder.typicode.com", 80, "http"); HttpGet request = new HttpGet("/posts/1"); request.addHeader("accept", "application/json"); CloseableHttpResponse response = null; try { response = client.execute(target, request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } reader = Json.createReader(new InputStreamReader((response.getEntity().getContent()))); JsonObject object = reader.readObject(); // System.out.println("raw : " + object.toString()) ; System.out.println("id : " + object.getJsonNumber("id")) ; System.out.println("title : " + object.getString("title")) ; /* output id : 1 title : sunt aut facere repellat provident occaecati excepturi optio reprehenderit Done. */ } finally { if (reader != null) reader.close(); if (client != null) client.close(); if (response != null) response.close(); System.out.println("Done."); } } }
The raw response looks like
[ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit ...eveniet architecto" } ... { "userId": 10, "id": 100, "title": "at nam consequatur ea labore ea harum", "body": "cupiditate quo est a modi nesciunt ... ratione error aut" } ]
import java.io.InputStreamReader; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; public class Json4 { public static void main(String args[]) throws Exception { Json4 x = new Json4(); x.doit(); } public void doit() throws Exception { JsonReader reader = null; CloseableHttpClient client = HttpClientBuilder.create().build(); HttpHost target = new HttpHost("jsonplaceholder.typicode.com", 80, "http"); HttpGet request = new HttpGet("/posts"); request.addHeader("accept", "application/json"); CloseableHttpResponse response = null; try { response = client.execute(target, request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } reader = Json.createReader(new InputStreamReader((response.getEntity().getContent()))); JsonArray array = reader.readArray(); for (int j = 0; j < array.size(); j++ ) { JsonObject jo = array.getJsonObject(j); System.out.println("id : " + jo.getJsonNumber("id")) ; System.out.println("title : " + jo.getString("title")) ; } /* output id : 1 title : sunt aut facere repellat provident occaecati excepturi optio reprehenderit ... id : 100 title : at nam consequatur ea labore ea harum Done. */ } finally { if (reader != null) reader.close(); if (client != null) client.close(); if (response != null) response.close(); System.out.println("Done."); } } }
import java.io.InputStream; import javax.json.Json; import javax.json.stream.JsonParser; import javax.json.stream.JsonParser.Event; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; //https://jsonp.java.net/download.html //http://hc.apache.org/downloads.cgi public class Json5 { public static void main(String args[]) throws Exception { Json5 x = new Json5(); x.doit(); } public void doit() throws Exception { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpHost target = new HttpHost("jsonplaceholder.typicode.com", 80, "http"); HttpGet request = new HttpGet("/posts"); request.addHeader("accept", "application/json"); CloseableHttpResponse response = null; try { response = client.execute(target, request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } InputStream is = response.getEntity().getContent(); JsonParser parser = Json.createParser(is); while (parser.hasNext()) { Event e = parser.next(); if (e == Event.KEY_NAME) { switch (parser.getString()) { case "id": parser.next(); System.out.print(parser.getString()); System.out.print(": "); break; case "title": parser.next(); System.out.println(parser.getString()); System.out.println("---------"); break; } } } /* output : 1: sunt aut facere repellat provident occaecati excepturi optio reprehenderit ------------- 2: qui est esse --------- ... 99: temporibus sit alias delectus eligendi possimus magni --------- 100: at nam consequatur ea labore ea harum --------- Done. */ } finally { if (client != null) client.close(); if (response != null) response.close(); System.out.println("Done."); } } }
Create a Java object from a JSON object
It's possible to do it by hand by calling the jasonobject.get[type] and the corresponding DTO/POJO set methods. But it is easier to use a library to handle the finer details. One library which is nice is GSON.In Maven project, use
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency>
Again from our REST example at jsonplaceholder.typicode.com/posts/1 , we define a DTO/POJO as :
public class JsonPlaceHolderPosts { int userid; int id; String title; String body; public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
import java.io.InputStreamReader; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import com.google.gson.Gson; // https://jsonp.java.net/download.html // http://hc.apache.org/downloads.cgi // http://search.maven.org/#artifactdetails|com.google.code.gson|gson|2.3.1|jar public class Json6 { public static void main(String args[]) throws Exception { Json6 x = new Json6(); x.doit(); } public void doit() throws Exception { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpHost target = new HttpHost("jsonplaceholder.typicode.com", 80, "http"); HttpGet request = new HttpGet("/posts/1"); request.addHeader("accept", "application/json"); CloseableHttpResponse response = null; try { response = client.execute(target, request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } Gson gson = new Gson(); JsonPlaceHolderPosts jphp = gson.fromJson(new InputStreamReader (response.getEntity().getContent()), JsonPlaceHolderPosts.class); System.out.println("id : " + jphp.getId()) ; System.out.println("title : " + jphp.getTitle()) ; /* ouput: id : 1 title : sunt aut facere repellat provident occaecati excepturi optio reprehenderit Done. */ } finally { if (client != null) client.close(); if (response != null) response.close(); System.out.println("Done."); } } }
Create a JSON string from a Java object
Finally, from a Java object, create a JSON string.import com.google.gson.Gson; // http://search.maven.org/#artifactdetails|com.google.code.gson|gson|2.3.1|jar public class Json7 { public static void main(String args[]) throws Exception { Json7 x = new Json7(); x.doit(); } public void doit() throws Exception { JsonPlaceHolderPosts jphp = new JsonPlaceHolderPosts(); jphp.setUserid(1111); jphp.setId(2222); jphp.setTitle("foo"); jphp.setBody("bar"); Gson gson = new Gson(); String json = gson.toJson(jphp, JsonPlaceHolderPosts.class); System.out.println("json : " + json) ; System.out.println("Done."); /* output : json : {"userid":1111,"id":2222,"title":"foo","body":"bar"} Done. */ } }