JSON in JavaEE 7

Hello guys..During week end i was doing lot of research on new technologies and newly released JavaEE 7 API. I found a very good enhancement in the API, i.e “JSON”. In modern day Programming when compared to lagecy apps the communication is completely depending on JSON data rather XML format, because of JSON’s readability and Object oriented nature. JSR-353 has bought a new feature in JavaEE 7, they included JSON API in JavaEE 7. Previous to JavaEE 7 most of us are relying on third party libs to form JSON structure now its all JavaEE 7 responsibility. I researched few things in the JSON(JavaEE 7) and here are my findings.

Note:Please add the following Maven dependency in you pom.xml file to get the JSON support from JavaEE 7

<dependencies>
	<dependency>
		<groupId>org.glassfish</groupId>
		<artifactId>javax.json</artifactId>
		<version>1.0.1</version>
	</dependency>
</dependencies>

JSON: is a text-based data exchange format derived from JavaScript that is used in web services and other connected applications.
The following example shows JSON data for a sample object that contains name-value pairs. The value for the name “phoneNumbers” is an array whose elements are two objects.

{
   "firstName": "PavanKumar",
   "lastName": "Mantha",
   "age": 27,
   "streetAddress": "100 JavaEE RandD",
   "city": "Hyderabad",
   "state": "AP",
   "postalCode": "12345",
   "phoneNumbers": [
      { "Mobile": "111-111-1111" },
      { "Home": "222-222-2222" }
   ]
}

JSON has the following syntax:

Objects are enclosed in braces {}, their name-value pairs are separated by a comma (,) and the name and value in a pair are separated by a colon (:). Names in an object are strings, whereas values may be of any of the six data types, including another object or an array.

Arrays are enclosed in brackets [], and their values are separated by a coma (,). Each value in an array may be of a different type, including another array or an object.

When objects and arrays contain other objects or arrays, the data has a tree-like structure.

Use of JSON:

JSON is commonly used to serialize and de-serialize object data and communicate over internet between two or more applications running in different environments, these application an be programmed in different languages but JSON can be a common platform to communicate. To my understanding this is the modern approach in compatible with legacy communication over XML.

Generating and Parsing JSON Data With Example
Note: please read JSR-353 support for JSON in JavaEE 7 oracle documentation for more details and API Spec.

Create JSONObject by reading Json data:

import java.io.FileReader;
import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonStructure;
...
JsonReader reader = Json.createReader(new FileReader("jsondata.txt"));
JsonStructure jsonst = reader.read();

Creating JSON Object from Application:

JsonObjectBuilder jsonObjectBuilder = (JsonObjectBuilder) Json
				.createObjectBuilder();
		JsonObject jsonObject = jsonObjectBuilder
				.add("firstName", "PavanKumar")
				.add("lastName", "Mantha")
				.add("age", 27)
				.add("streetAddress", "100 JavaEE RandD")
				.add("city", "Hyderabad")
				.add("state", "AP")
				.add("postalCode", "12345")
				.add("phoneNumbers",
						Json.createArrayBuilder()
								.add(Json.createObjectBuilder()
										.add("type", "mobile")
										.add("number", "111-111-1111"))
								.add(Json.createObjectBuilder()
										.add("type", "home")
										.add("number", "222-222-2222")))
				.build();

Traversing a JSON Object:

public static void navigateTree(JsonValue tree, String key) {
		if (key != null)
			System.out.print("Key " + key + ": ");
		switch (tree.getValueType()) {
		case OBJECT:
			System.out.println("OBJECT");
			JsonObject object = (JsonObject) tree;
			for (String name : object.keySet())
				navigateTree(object.get(name), name);
			break;
		case ARRAY:
			System.out.println("ARRAY");
			JsonArray array = (JsonArray) tree;
			for (JsonValue val : array)
				navigateTree(val, null);
			break;
		case STRING:
			JsonString st = (JsonString) tree;
			System.out.println("STRING " + st.getString());
			break;
		case NUMBER:
			JsonNumber num = (JsonNumber) tree;
			System.out.println("NUMBER " + num.toString());
			break;
		case TRUE:
		case FALSE:
		case NULL:
			System.out.println(tree.getValueType().toString());
			break;
		}

	}

How to write JSON Object to Stream?

try {
			StringWriter stringWriter = new StringWriter();
			JsonWriter jsonWriter = Json.createWriter(stringWriter);
			jsonWriter.writeObject(jsonObject);
			jsonWriter.close();

			FileWriter fileWriter = new FileWriter(new File("D:\\jsonDate.txt"));
			fileWriter.write(stringWriter.toString());
			fileWriter.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

Parsing Json Object Data:

JsonParser jsonParser = Json.createParser(new StringReader(
				jsonModelString.toString()));
		while (jsonParser.hasNext()) {
			JsonParser.Event event = jsonParser.next();
			if (event == event.KEY_NAME) {
				System.out.print(event.toString() + " "
						+ jsonParser.getString() + " - ");
			} else if (event == event.VALUE_NUMBER) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			} else if (event == event.VALUE_STRING) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			}
		}

Now the following is the complete picture of the above concepts

/**
 * 
 */
package com.spark.javaee;

import java.io.File;
import java.io.FileWriter;
import java.io.StringReader;
import java.io.StringWriter;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonString;
import javax.json.JsonValue;
import javax.json.JsonWriter;
import javax.json.stream.JsonGenerator;
import javax.json.stream.JsonParser;

/**
 * @author Sony
 * 
 */
public class JsonJavaeeApiDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		JsonJavaeeApiDemo javaeeApiDemo = new JsonJavaeeApiDemo();
		JsonObject jsonObject = javaeeApiDemo.createJsonObject();
		javaeeApiDemo.createJsonDataFile(jsonObject);
		javaeeApiDemo.iterateObjectModel(jsonObject.toString());
		System.out.println("===============================================");
		javaeeApiDemo.generateJsonData(jsonObject);
		JsonJavaeeApiDemo.navigateTree(jsonObject, jsonObject.toString());
	}

	public void iterateObjectModel(String jsonModelString) {
		JsonParser jsonParser = Json.createParser(new StringReader(
				jsonModelString.toString()));
		while (jsonParser.hasNext()) {
			JsonParser.Event event = jsonParser.next();
			if (event == event.KEY_NAME) {
				System.out.print(event.toString() + " "
						+ jsonParser.getString() + " - ");
			} else if (event == event.VALUE_NUMBER) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			} else if (event == event.VALUE_STRING) {
				System.out.println(event.toString() + " "
						+ jsonParser.getString());
			}
		}
	}

	public JsonObject createJsonObject() {

		JsonObjectBuilder jsonObjectBuilder = (JsonObjectBuilder) Json
				.createObjectBuilder();
		JsonObject jsonObject = jsonObjectBuilder
				.add("firstName", "PavanKumar")
				.add("lastName", "Mantha")
				.add("age", 27)
				.add("streetAddress", "100 JavaEE RandD")
				.add("city", "Hyderabad")
				.add("state", "AP")
				.add("postalCode", "12345")
				.add("phoneNumbers",
						Json.createArrayBuilder()
								.add(Json.createObjectBuilder()
										.add("type", "mobile")
										.add("number", "111-111-1111"))
								.add(Json.createObjectBuilder()
										.add("type", "home")
										.add("number", "222-222-2222")))
				.build();
		return jsonObject;
	}

	public static void navigateTree(JsonValue tree, String key) {
		if (key != null)
			System.out.print("Key " + key + ": ");
		switch (tree.getValueType()) {
		case OBJECT:
			System.out.println("OBJECT");
			JsonObject object = (JsonObject) tree;
			for (String name : object.keySet())
				navigateTree(object.get(name), name);
			break;
		case ARRAY:
			System.out.println("ARRAY");
			JsonArray array = (JsonArray) tree;
			for (JsonValue val : array)
				navigateTree(val, null);
			break;
		case STRING:
			JsonString st = (JsonString) tree;
			System.out.println("STRING " + st.getString());
			break;
		case NUMBER:
			JsonNumber num = (JsonNumber) tree;
			System.out.println("NUMBER " + num.toString());
			break;
		case TRUE:
		case FALSE:
		case NULL:
			System.out.println(tree.getValueType().toString());
			break;
		}

	}

	public void createJsonDataFile(JsonObject jsonObject) {
		try {
			StringWriter stringWriter = new StringWriter();
			JsonWriter jsonWriter = Json.createWriter(stringWriter);
			jsonWriter.writeObject(jsonObject);
			jsonWriter.close();

			FileWriter fileWriter = new FileWriter(new File("D:\\jsonDate.txt"));
			fileWriter.write(stringWriter.toString());
			fileWriter.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void generateJsonData(JsonObject jsonObject) {
		try {
			FileWriter writer = new FileWriter("D:\\test.txt");
			JsonGenerator gen = Json.createGenerator(writer);
			gen.writeStartObject().write("firstName", "PavanKumar")
					.write("lastName", "Mantha").write("age", 27)
					.write("streetAddress", "100 javaEE RandD")
					.write("city", "JavaCity").write("state", "AP")
					.write("postalCode", "12345")
					.writeStartArray("phoneNumbers").writeStartObject()
					.write("type", "mobile").write("number", "111-111-1111")
					.writeEnd().writeStartObject().write("type", "home")
					.write("number", "222-222-2222").writeEnd().writeEnd()
					.writeEnd();
			gen.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

Happy Coding with JSON 🙂

courtesy: Oracle docs
ref:http://docs.oracle.com/javaee/7/tutorial/doc/jsonp.htm#GLRBB

Advertisements

One thought on “JSON in JavaEE 7

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s