Java, JSON

Parsing JSON using Gson in Java

In this article we will look into parsing JSON using Gson in Java. Gson is a Java library that can be used to convert a JSON string to an equivalent Java object. It can also be used to convert Java objects into their JSON representation.

If you are using Maven, add the following dependency in pom.xml.

		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.2.2</version>
		</dependency>

If you are not using Maven, download the Gson JAR files from here, and add them to the class path.

This is a sample JSON that we will try processing in this article.

{
   "widgets":{
      "window":{
         "title":"Sample Konfabulator Widget",
         "name":"main_window",
         "width":500,
         "height":500,
         "messages":[
            "Ok",
            "Cancel"
         ]
      },
      "image":{
         "title":"Sun's Image",
         "name":"sun1",
         "width":200,
         "height":300
      },
      "text":{
         "title":"Devesh Sharma",
         "name":"txt1",
         "width":100,
         "height":100
      }
   }
}

Now, in order to convert the JSON into equivalent Java objects, we will have to create Java beans first.

Looking at the JSON it is clear that we are dealing with ‘Widgets’ here, and window, image and text are ‘Widget’.

title, name, width and height are attributes of ‘Widget’.

Based on this information, let’s create 2 Java bean classes: Widgets and Widget.

Widgets.java:

public class Widgets {
	
	private Map<String, Widget> widgets;
	
	public Map<String, Widget> getWidgets() {
		return widgets;
	}

	public void setWidgets(Map<String, Widget> widgets) {
		this.widgets = widgets;
	}
}

Widget.java

public class Widget {

	private String title;
	private String name;
	private long width;
	private long height;
	private List<String> messages;
	
	public String getTitle() {
		return title;
	}
	
	public void setTitle(String title) {
		this.title = title;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public long getWidth() {
		return width;
	}
	
	public void setWidth(long width) {
		this.width = width;
	}
	
	public long getHeight() {
		return height;
	}
	
	public void setHeight(long height) {
		this.height = height;
	}

	public List<String> getMessages() {
		return messages;
	}

	public void setMessages(List<String> messages) {
		this.messages = messages;
	}
}

Now we have everything to process the JSON. Here is the code to process the sample JSON:

	public static void main(String[] args) {

		BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader("resources/sampleJSON.txt"));

			String line = null;
			
			while ((line = reader.readLine()) != null) {
				
				Gson gson = new Gson();
				Widgets widgets = gson.fromJson(line, Widgets.class);
				
				for(Map.Entry<String, Widget> entry : widgets.getWidgets().entrySet()) {
					
					String widgetType = entry.getKey();
					Widget widget = entry.getValue();
					List<String> messages = widget.getMessages();
					
					System.out.println("Widget: " +widgetType);
					
					System.out.println("Attributes:");
					System.out.println("Title: " +widget.getTitle());
					System.out.println("Name: " + widget.getName());
					System.out.println("Width: " + widget.getWidth());
					System.out.println("Height: " + widget.getHeight());
					
					if(messages != null) {
						
						System.out.println("Messages:");
						for(String message : messages) {
							System.out.println("* "+message);
						}
					}
					System.out.println();
					System.out.println();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

Please make sure that you get rid of spaces when you copy the sample JSON to resources/sampleJSON.txt file.

Here is the output:

Widget: window
Attributes:
Title: Sample Konfabulator Widget
Name: main_window
Width: 500
Height: 500
Messages:
* Ok
* Cancel

Widget: image
Attributes:
Title: Sun’s Image
Name: sun1
Width: 200
Height: 300

Widget: text
Attributes:
Title: Devesh Sharma
Name: txt1
Width: 100
Height: 100

Java, JSON

Returning a JSON object from a Java Servlet

The only important thing to keep in mind while returning a JSON object from a Java servlet is to specify the correct MIME type for JSON. The correct MIME type for JSON is application/json.

Therefore, while returning a JSON object from a servlet you need to set the content type like this:

       response.setContentType("application/json");

For your convenience I am attaching a sample code.

	public void doGet(
			HttpServletRequest request,
			HttpServletResponse response
	) {
		
		try {
			response.setContentType("application/json");
			PrintWriter out = response.getWriter();
			out.println("{");
			out.println("\"First Name\": \"Devesh\",");
			out.println("\"Last Name\": \"Sharma\"");
			out.println("}");
            out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}