String to JSON in Java

How to convert JSON string to JSON object in java?

There are various ways using we can convert a string to json in java. Some of the methods are listed below. If you need to process a small amount of data from and into JSON format then you should consider using Gson or flexjson. If you need to process large amounts of data from and into JSON format then using JSON-lib or Jackson is a wise choice.Lets consider another example
json_String = {
  "name" : "MS Dhoni",
  "sport" : "Cricket",
  "age" : 37,
  "id" : 101,
  "Scores" : [ 27, 50, 178, 91, 25, 42, 58, 101 ]
}
This is simple example, it has 5 attributes which are two strings, two numeric and a JSON array.

1. String to JSON Object using Gson

The Gson is open source library to deal with JSON in java programming language. It is developed by Google. This is very simple method to convert JSON string to Java object with a small piece of code using Gson.
Gson g1 = new Gson();
Player p1 = g.fromJson(json_String, Player.class)
To convert a java object to JSON you can use toJson() method as shown below
String str = g.toJson(p1);
You must know the basics of JSON before handling JSON conversions in java. If you don't understand JSON format at all, I would suggest reading Beginning JSON by Ben Smit to learn about it.

2. JSON String to JSON Object Using org.json library

Suppose you have a string variable named myString
{"name":"Robert","gender":"male"}
we can convert it to JSON object as follows
try
{
	JSONObject json_Object = new JSONObject("{\"name\":\"Robert\",\"gender\":\"male\"}");
}
catch (JSONException err)
{
	Log.d("Error", err.toString());
}

3. String to JSON using Jackson

Jackson is a high-performance JSON processor for Java. Its developers extol the combination of fast, correct, lightweight, and ergonomic attributes of the library. It's fast, feature rich and supports streaming which is great for parsing large JSON output from web services. Following example converts JOSN String to Java class.
Player Messi= new ObjectMapper().readValue(jsonString, Player.class);
The main advantages of using Jackson library is that it supports streaming which can be used to parse huge JSON response without loading it fully in memory. Jackson does not support J2ME, also it requires JDK 1.5, if you are using previous java versions then Jackson is not recommended for you.

4. JSON String to Java Object Using JSON-lib

JSON-lib is a java library used for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans. It is based on the work by Douglas Crockford.

In JSON-lib using JSONSerializer we can transform any JSON notation to Java object and vice versa very easily. To transform a valid JSON value (object) use toJava() method. To transform a Java object into JSON use JSONSerializer.toJSON() method. The serializer needs special configuration to transform a JSON value to a bean class, array, List or DynaBean, so the method used for this is an instance method.

Consider you have a JSON string
static String json = "{\"name\":\"Dhoni\",\"profession\":\"cricketer\"}";

There are two ways to convert your JSON string to java object,

1. Convert to Dynabean and then to java object

JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( json );  
DynaBean bean = (DynaBean) JSONSerializer.toJava( jsonObject );

2. Convert to java object directly

JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( json );
Map myMap = (Map) JSONObject.toBean(jsonObject, Map.class)

5. JSON String to Java Object Using JSON-Simple

JSON.simple is a small sized simple Java library for JSON parsing, formatting, reading and writing JSON data. It suitable for restricted memory environments like Android.
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
The advantage (if considered) of JSON-simple is that it is JDK 1.2 compatible so that you can work on legacy projects also.

Additional Mehtod: JSON String to Java Object Using Flexjson Example

Flexjson is another lightweight library for serializing and deserializing Java objects into and from JSON format allowing both deep and shallow copies of objects. Flexjson is a lightweight library for serializing Java objects into JSON. The advantage of Flexjson is it's control over what gets serialized allowing both deep and shallow copies of objects. As we can control the depth it allows us only to extract the information we need. This is very similar to lazy-loading.
public class watch{
    public int watchID;

    public watch(){}

    public watch(int pwatchID){
        this.watchID=pwacthID;
    }
}
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

public class DeserializerTest {
	public static void main(String[] args)
	{
		JSONSerializer serilizer = new JSONSerializer();
		watch watch1 = new watch(123);
		String watchString = serilizer.serialize(watch1);

		watch deserializedwatch = new JSONDeserializer().deserialize( watchString );
		System.out.println("watchID: "+deserializedwatch.watchID);
	}
}
You can read and learn more about how to parse JSON string to Java object or JSON String to JSON object in java using these libraries with this book byDeveloping RESTful Services with JSON