-> toJson() – convert java object to JSON format
-> fromJson() – convert JSON into java object
import com.google.gson.Gson;
public class TestObjectToJson {
private int data1 = 100;
private String data2 = "hello";
public static void main(String[] args) {
TestObjectToJson obj = new TestObjectToJson();
Gson gson = new Gson();
//convert java object to JSON format
String json = gson.toJson(obj);
System.out.println(json);
}
}
Output
{"data1":100,"data2":"hello"}
As, we all know we can get data in JSON string format easily from the REST , SOAP or other Java web services instead of XML and it does not convert JSON string to JSON object directly and it is not convenient to use JSON string every time then sometimes, it is required to convert JSON String to JSON object in java for retrieving values.
How to convert String to a JSON object in Java ?
There are three rich open source libraries that allow you to convert String to JSON object efficiently and the name of the three libraries are given below:
Gson Libraries(Comes From Google)
JSON-Simple Libraries
JACKSON Libraries
Before using any of the above libraries, you need to set the classpath of the relevant jar file.
For Gson Libraries, you need to set the classpath of Gson.jar file and you can refer to this link http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm for downloading .
For JSON-Simple Libraries, you need to set the classpath of Json.jar file and you can refer to this link http://www.java2s.com/Code/Jar/j/Downloadjsonsimple11jar.htm for downloading.
For JACKSON Libraries, you need to set the classpath of jackson.jar file and you can refer to this link http://www.java2s.com/Code/Jar/c/Downloadcomfasterxmljacksoncorejar.htm and http://www.java2s.com/Code/Jar/c/Downloadcomfasterxmljacksondatabindjar.htm for downloading.
All the above libraries can be used to convert String to JSON objects and we will explain all the above libraries with the help of an example but you can choose any of the above libraries for String to JSON object conversion.
Example 1: Java program is used to convert String to JSON object using Gson Libraries
import com.google.gson.Gson;
public class GSONProgram {
public static void main(String[] args) {
/* Creating a String named "json_str"
in JSON format*/
String json_str = "{ \"Employee_Name\": \"PREETI\", "
+ " \"Employee_Salary\": 80000}";
/* Let's see how to convert String to JSON
object using GSON open source libraries*/
Gson g_son = new Gson();
/* Convert JSON String to Java object */
Employee emp_ob = g_son.fromJson(json_str, Employee.class);
System.out.print("Conversion of String to JSON object");
System.out.println(" "+"using Gson Libraries: ");
/* Convert Java object to JSON */
json_str = g_son.toJson(emp_ob);
System.out.println(json_str);
System.out.println();
/* Display Employee_Name and Employee_Salary */
System.out.println("Retrieves Values: ");
System.out.print("Employee Name: ");
System.out.println(emp_ob.getEmployeeName());
System.out.print("Employee Salary: ");
System.out.println(emp_ob.getEmployeeSalary());
}
}
class Employee{
private String Employee_Name;
private int Employee_Salary;
public Employee() {};
public void setEmployeeName(String Employee_Name) {
this.Employee_Name = Employee_Name;
}
public String getEmployeeName() {
return Employee_Name;
}
public void setEmployeeSalary(int Employee_Salary) {
this.Employee_Salary = Employee_Salary;
}
public int getEmployeeSalary() {
return Employee_Salary;
}
}
Output:
Conversion of String to JSON object using Gson Libraries:
{"Employee_Name":"PREETI","Employee_Salary":80000}
Retrieves Values:
Employee Name: PREETI
Employee Salary: 80000
Example 2: Java program is used to convert String to JSON object using JSON-Simple Libraries
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JSONSimpleProgram {
public static void main(String[] args) throws Exception{
/* Creating a String named "json_str"
in JSON format*/
String json_str = "{ \"Employee_Name\": \"PREETI\", "
+ " \"Employee_Salary\": 80000}";
/* Let's see how to convert String to JSON
object using JSON-Simple open source libraries*/
System.out.print("Conversion of String to JSON object");
System.out.println(" "+"using JSON-Simple Libraries: ");
JSONParser json_parser = new JSONParser();
JSONObject json_ob = (JSONObject)json_parser.parse(json_str);
/* Display JSONObject */
System.out.println(json_ob);
System.out.println();
/* Retrieve values from JSON object */
System.out.println("Retrieves Values: ");
String emp_name = (String)json_ob.get("Employee_Name");
long salary = (long)json_ob.get("Employee_Salary");
/* Display Employee Name and Employee Contact */
System.out.println("Employee Name: "+emp_name);
System.out.println("Employee Salary: "+ salary);
System.out.println();
}
}
Output:
Conversion of String to JSON object using JSON-Simple Libraries:
{"Employee_Salary":80000,"Employee_Name":"PREETI"}
Retrieves Values:
Employee Name: PREETI
Employee Salary: 80000
Example 3: Java program is used to convert String to JSON object using Jackson Libraries
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonClass {
public static void main(String[] args) throws Exception {
/* Creating a String named "employee"
in JSON format*/
String json = "{ \"productName\": \"DELL\", "
+ " \"productPrice\": 50000}";
/* Let's see how to convert String to JSON
object using GSON open source libraries*/
ObjectMapper ob_mapper = new ObjectMapper();
/* Convert JSON String to Java object */
Sales sell = ob_mapper.readValue(json, Sales.class);
System.out.print("Conversion of String to JSON object");
System.out.println(" "+"using Jackson Libraries: ");
/* Convert Java object to JSON */
System.out.println(ob_mapper.writeValueAsString(sell));
System.out.println();
/* Display productName and productSalary */
System.out.println("Retrieves Values: ");
System.out.print("Product Name: ");
System.out.println(sell.getProductName());
System.out.print("Product Price: ");
System.out.println(sell.getProductPrice());
}
}
class Sales{
private String productName;
private int productPrice;
public Sales(){};
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductName() {
return productName;
}
public void setProductPrice(int productPrice) {
this.productPrice = productPrice;
}
public int getProductPrice() {
return productPrice;
}
}
Output:
Conversion of String to JSON object using Jackson Libraries:
{"productName":"DELL","productPrice":50000}
Retrieves Values:
Product Name: DELL
Product Price: 50000
If you want to unleash your potential in this competitive field, please visit the Java Certification Training page for more information, where you can find the and Java Interview Questions FAQ's and answers as well.
For more updates on the latest courses stay tuned to HKR Trainings.