JSON serialization and Deserialization
Persist JSON to Java Object /POJO called JSON serialization ( Storing object state in a file ).
Converting Java object / POJO to JSON object called JSON Deserialization ( reading/recreating from file to object ).
Gson ( Google JSON library) used to convert object to/from json.
Gson is easy to learn and implement, what we need to know are following two methods.
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object
Maven dependency to add to POM.xml ( search for latest jar in maven central ..http://search.maven.org/#search%7Cga%7C1%7Cgson )
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.4</version>
</dependency>
POJO
import java.util.ArrayList;
import java.util.List;
public class VarObject {
private int var1= 1599;
private String var2 = "GsonWelcomesU";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods
@Override
public String toString() {
return "DataObject [var1=" + var1 + ", var2=" + var2 + ", list="
+ list + "]";
}
}
Serialize JSON .. toJson()
Convert object to JSON string, and save it as “file.json“.
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
public class SerializeJSON {
public static void main(String[] args) {
VarObject obj = new VarObject ();
Gson gson = new Gson();
// convert java object to JSON format, and returned as JSON formatted string
String json = gson.toJson(obj);
try {
//write converted json data to a file named "file.json"
FileWriter writer = new FileWriter("c:\\file.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(json);
}
}
Output
{"var1":1599,"var2":"GsonWelcomesU","list":["String 1","String 2","String 3"]}
DeSerialize JSON .. fromJson()
Convert JSON to Java Object.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
public class DeserializeJSON {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(
new FileReader("c:\\file.json"));
//convert the json string back to object
VarObject obj = gson.fromJson(br, VarObject.class);
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
VarObject [var1=1599, var2=GsonWelcomesU, list=[String 1, String 2, String 3]]
Pretty Print JSON format
To enable pretty print, you should use GsonBuilder
return a Gson
object :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);
System.out.println(json);
Output
{
"var1": 1599,
"var2": "GsonWelcomesU",
"list": [
"String 1",
"String 2",
"String 3"
]
}
********* How to convert a long JSON Array to Java Object ?? *********
No comments:
Post a Comment