In this Tutorials we are going to see how to convert JSON String to Java object using GSON library.
1. Create project called JSONExample.
2. Create package called com.javatutorialscorner.gson
3. Create java class called GsonPojo under com.javatutorialscorner.gson.
GsonPojo.java
GsonPojo is Pojo class.
package com.javatutorialscorner.gson;
import java.util.List;
public class GsonPojo {
private int var1 = 10;
private String var2;
private List<String> list;
public int getVar1() {
return var1;
}
public void setVar1(int var1) {
this.var1 = var1;
}
public String getVar2() {
return var2;
}
public void setVar2(String var2) {
this.var2 = var2;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
4. Now Create class called GSONExample under com.javatutorialscorner.gson.
GSONExample.java
This main class.
package com.javatutorialscorner.gson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.Gson;
public class GSONExample {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Gson gson = null;
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\jtc\\javatutorialscorner.json"));
gson = new Gson();
GsonPojo pojo = gson.fromJson(br, GsonPojo.class);
System.out.println("var1 : " + pojo.getVar1());
System.out.println("var2 : " + pojo.getVar2());
System.out.println("list : " + pojo.getList());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now run the program see the following output in console.
var1 : 10
var2 : Java Tutorials Corner
list : [Java, Sevlet, JSP, JSF, Struts 1.x, Struts 2.x, Tiles, Spring, Hibernate]
0 comments:
Post a Comment