25
Nov
10

Converting Java Object to JSON String


This page covers the process of converting Java Objects to JSON Strings. And JSON Strings back to Java Objects. I will also cover how to do the conversion with ArrayList of objects.

Background

JSON is becoming a popular way to transmit data between Web Applications and User Agents (Browsers, mobile apps etc…). I have gotten into Experimenting with Android applications so I thought it would be a nice idea to write some stuff about JSON and how its used with Java.

This page contains a working “Java Main” application that you can run from command line.

Requirements

  • Java 5 or above
  • Maven 2

Create the project

I will be creating this project using Maven but you can simply find the JSON libraries and install it in the classpath and follow along.

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart

For the group id enter: com.test
For the artifactId enter: jsonTest

Answer the rest of the questions using defaults [Hit Enter].

cd to the project’s folder

Next we create the src/main/java folder since this is not done for us using the archetype.

on unix you type:

cd jsonTest
mkdir -p src/main/java
mkdir -p src/main/java/com/test

Project Configuration

Modify the configuration and verify that it looks something like this.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test</groupId>
  <artifactId>jsonTest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>jsonTest</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>
  </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Address Bean

We start by creating the Address Bean.

src/main/java/com/test/Address.java

package com.test;

public class Address {
	private String street;
	private String city;
	private String state;
	private String zip;
	
	public Address(String street, String city, String state, String zip) {
		this.street = street;
		this.city = city;
		this.state = state;
		this.zip = zip;
	}
	public String getStreet() {
		return street;
	}
	public String getCity() {
		return city;
	}
	public String getState() {
		return state;
	}
	public String getZip() {
		return zip;
	}
	public String toString() {
		return "Address [city=" + city + ", state=" + state + ", street="
				+ street + ", zip=" + zip + "]";
	}
}

Create the AddressDataManager

This class is responsible for managing instances of the address class. This class encapsulates all the JSON operations away from the Address Java Bean. It doesn’t exactly follow the “Spring Framework’s” way of doing things but it could be enhanced to work with the spring framework.

src/main/java/com/test/AddressDataManager.java

package com.test;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class AddressDataManager {
	public List<Address> parseJSONArrayAddressList(String jsonString) {
		List<Address> parsedAddressList = new ArrayList<Address>();

		try {
			JSONArray jsonArray2 = new JSONArray(jsonString);
			int length = jsonArray2.length();			
			for(int i=0; i< length; i++) {
				JSONObject a = (JSONObject)jsonArray2.get(1);
				parsedAddressList.add(parseJSONObject(a));
			}
			return parsedAddressList;
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
	}

	public Address parseJSONObject(JSONObject a) throws JSONException {
		Address address = new Address(
				a.getString("street"), 
				a.getString("city"), 
				a.getString("state"), 
				a.getString("zip"));
		return address;
	}
}

Test Class

Finally this is our test class that pretty much runs the show. Reading the comments is the best way to follow along.

src/main/java/com/test/TestActivity.java

package com.test;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class TestActivity {
	
	public static void main(String args[]) {
		
		AddressDataManager addressDataManager = new AddressDataManager();
		
		Address a1 = new Address("100 Main Street", "New York", "NY", "10010");
		Address a2 = new Address("110 Main Street", "New York", "NY", "12345");
		Address a3 = new Address("4 Chestnut Street", "New York", "NY", "54321");
		
		// convert a object into a string
		System.out.println("JSON String: " + new JSONObject(a1).toString());
		
		// convert a string into an object
		String singleAddressJSON = 
			"{\"zip\":\"10010\",\"street\":\"100 Main Street\",\"state\":\"NY\",\"city\":\"New York\"}";

		try {
			System.out.println("Address Object: " + 
					addressDataManager.parseJSONObject(new JSONObject(singleAddressJSON)));
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
		
		// convert an ArrayList into a json array
		java.util.List<JSONObject> addressList = 
			new java.util.ArrayList<JSONObject>();

		addressList.add(new JSONObject(a1));
		addressList.add(new JSONObject(a2));
		addressList.add(new JSONObject(a3));
		
		JSONArray jsonArray = new JSONArray(addressList);
		System.out.println(jsonArray.toString());
		
		// convert JSON array to ArrayList
		final String jsonString = 
			"[{\"zip\":\"10010\",\"street\":\"100 Main Street\",\"state\":\"NY\"" +
			",\"city\":\"New York\"},{\"zip\":\"12345\",\"street\":\"110 Main Street\"" +
			",\"state\":\"NY\",\"city\":\"New York\"},{\"zip\":\"54321\",\"street\"" +
			":\"4 Chestnut Street\",\"state\":\"NY\",\"city\":\"New York\"}]";

		List<Address> parsedAddressList = addressDataManager.parseJSONArrayAddressList(jsonString);		
		System.out.println("This is the arrayList: " + parsedAddressList);
	}
}

Run the project

mvn clean compile exec:java -Dexec.mainClass=com.test.TestActivity

You should see output like this…

JSON String: {"zip":"10010","street":"100 Main Street","state":"NY","city":"New York"}
Address Object: Address [city=New York, state=NY, street=100 Main Street, zip=10010]
[{"zip":"10010","street":"100 Main Street","state":"NY","city":"New York"},{"zip":"12345","street":"110 Main Street","state":"NY","city":"New York"},{"zip":"54321","street":"4 Chestnut Street","state":"NY","city":"New York"}]
This is the arrayList: [Address [city=New York, state=NY, street=110 Main Street, zip=12345], Address [city=New York, state=NY, street=110 Main Street, zip=12345], Address [city=New York, state=NY, street=110 Main Street, zip=12345]]

Thats all for now.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 77 other followers

November 2010
S M T W T F S
« Oct   Dec »
 123456
78910111213
14151617181920
21222324252627
282930  

Blog Stats

  • 846,577 hits

%d bloggers like this: