Skip to content

Instantly share code, notes, and snippets.

toJson ---
Original Java object : ModelObject [name=myname, val=12, status=true, f=2.3]
Converted JSON string is : {"name":"myname","val":12,"status":true,"f":2.3}
fromJson----
Original JSON string is : {"name":"myname","val":12,"status":true,"f":2.3}
Converted Java object : ModelObject [name=myname, val=12, status=true, f=2.3]
package in.ajduke.ap012;
/**
* An model for gson demo
*
* @author ajduke
*/
public class ModelObject {
String name;
int val;
boolean status;
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.code.gson:gson:2.2.4'
}
package in.ajduke.ap012;
/**
* An generified model for demo of gson conversion
* @author ajduke
*/
public class GenericModel<T> {
T value;
public GenericModel(T value) {
super();
Gson gson = new Gson();
System.out.println("A generic object demo");
// a generified object
GenericModel<Integer> model = new GenericModel<>(12);
// converting to json representation
String json = gson.toJson(model);
System.out.println("json representation :" + json);
A generic object demo
json representation :{"value":12}
converted object representation: Model2 [value=12]
A object from collection framework
json representation :["ajduke","ajduchess"]
converted object representation: [ajduke, ajduchess]
package in.ajduke.ap012;
/**
* An model for demo of gson conversion
*
* @author ajduke
*/
public class ModelObject {
String name;
transient int val;
boolean status;
Gson gson = new Gson();
// original object
ModelObject modelObject = new ModelObject("namesake", 50, true, 4.3);
System.out.print("Original Java object : ");
System.out.println(modelObject);
// converting to an json representation
String json = gson.toJson(modelObject);
System.out.print("Converted JSON string is : ");
System.out.println(json);
Original Java object : ModelObject [name=namesake, val=50, status=true, f=4.3]
Converted JSON string is : {"name":"namesake","status":true,"f":4.3}
Converted Java object : ModelObject [name=namesake, val=0, status=true, f=4.3]