Java JSON

The json.simple library permits us to read and write JSON information in Java. As such, we can encode and disentangle JSON object in java utilizing json.simple library.

The org.json.simple bundle contains vital classes for JSON API.

  • JSONValue
  • JSONObject
  • JSONArray
  • JsonString
  • JsonNumber

To introduce json.simple, you have to set classpath of json-simple.jar or include the Maven reliance.

To add maven dependency, write the following code in pom.xml file.

	
<dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1</version>
 </dependency>
 

Java JSON Encode

	
 import org.json.simple.JSONObject;    
public class JsonExample{    
public static void main(String args[]){    
JSONObject obj=new JSONObject();    
  obj.put("name","mithilesh");    
  obj.put("age",new Integer(24));    
  obj.put("salary",new Double(5000));    
   System.out.print(obj);    
}}    
		

Output-

{"name":"mithilesh","salary":5000,"age":24}

Java JSON Array Encode

 import org.json.simple.JSONArray;  
public class JsonExample {    
public static void main(String args[]){    
  JSONArray arr = new JSONArray();  
  arr.add("Mithilesh");    
  arr.add(new Integer(24));    
  arr.add(new Double(5000));   
  System.out.print(arr);  
}}    

Output-

["Mithilesh ",24,5000.0]

Java JSON Array Encode using List

	
 import java.util.ArrayList;  
import java.util.List;  
import org.json.simple.JSONValue;  
public class JsonExample {    
public static void main(String args[]){    
  List arr = new ArrayList();  
  arr.add("Mithilesh");    
  arr.add(new Integer(24));    
  arr.add(new Double(5000));   
  String jsonText = JSONValue.toJSONString(arr);  
  System.out.print(jsonText);  
}}  
		

Output -

["Mithilesh",24,5000.0]

Java JSON Decode

	
		import org.json.simple.JSONObject;  
import org.json.simple.JSONValue;  
public class JsonDecodeExample  {  
public static void main(String[] args) {  
    String s="{\"name\":\"Mithilesh\",\"salary\":5000.0,\"age\":24}";  
    Object obj=JSONValue.parse(s);  
    JSONObject jsonObject = (JSONObject) obj;  
  
    String name = (String) jsonObject.get("name");  
    double salary = (Double) jsonObject.get("salary");  
    long age = (Long) jsonObject.get("age");  
    System.out.println(name+" "+salary+" "+age);  
}  
}  
Mithilesh 5000.0 24