• Home
  • Basics
  • DSA
  • MAD
  • Concept
  • Practice
  • Misc
    • Tips
    • QA’s
    • Misc
  • Course
  • Home
  • Basics
  • DSA
  • MAD
  • Concept
  • Practice
  • Misc
    • Tips
    • QA’s
    • Misc
  • Course
  • #News
  • #APPS
  • #Apple WWDC
  • #Google I/O
  • #Microsoft Ignite
  • #Let’s Talk
  • #Advertise

MyCodeTips mycodetips-newlogocopy1

  • Home
  • Basics
  • DSA
  • MAD
  • Concept
  • Practice
  • Misc
    • Tips
    • QA’s
    • Misc
  • Course
Programming

Google Gson for converting Java objects to JSON and JSON to Java Objects

Google Gson for converting Java objects to JSON and JSON to Java Objects

Java objects to JSON and JSON to Java Objects : Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Gson is an Open Source project, which can be found under https://github.com/google/gson The webpage provides a convenient download link.

Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. For this purpose Gson provides several built in serializers and deserializers. A serializer allows to convert a Json string to corresponding Java type and a deserializers allows to convert from Java to a JSON representation. You can also configure Gson to use custom representations of your objects.

Gson allows to serialize a Collections of objects of the same type. As the generics information is persisted in the JSON you need to specify the type to which you want to serialize too. For this you have different options.

To use Gson in a Gradle build, add compile ‘com.google.code.gson:gson:2.6.2’ or a later version as dependency to your build.gradl e build file

Excluding fields from serialization and deserialization
By default, Gson tries to map all fields in the Java object to the JSON file it creates and vice versa. But Gson allows to exclude certain fields for serialization and deserialization. GSon can for example not serialize Java Beans, as the IPropertyChangeSupport field lead to an infinite loop. Therefore you must exclude such a field from the JSON conversion.

To exclude fields you have four options:

Use the transient keyword on your field to indicate that this field not not be serialized.

Gson provides an the @Expose from the com.google.gson.annotations package which allows to define which fields should be deserialized. You can configure Gson to consider this annotation.

You can register a custom exclusion strategy with the GsonBuilder and its setExclusionStrategies method. For this you would implement the ExclusionStrategy and its houldSkipField(FieldAttributes f) and shouldSkipClass(Class clazz) methods.

You can define a custom annotation and tell GSon to ignore such fields.

Exercise: Using Gson
Target of this exercise
In this exercise you use Gson to convert a data model into JSON and the JSON back to Java objects.

Create project and add library to it
Create a Java project, download the Gson library from its homepage and add it to the projects classpath.

Create the data model

Create the following data model.

package com.mycodetips.java.library.gson;

public class Task {
private final long id;
private String summary;
private String description;
private Status status;
private int priority;

public enum Status {
CREATED, ASSIGNED, CANCELED, COMPLETED
}

public Task(long id, String summary, String description, Status status, int priority) {
this.id = id;
this.summary = summary;
this.description = description;
this.status = status;
this.priority = priority;
}

public long getId() {
return id;
}

public String getSummary() {
return summary;
}

public void setSummary(String summary) {
this.summary = summary;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Status getStatus() {
return status;
}

public void setStatus(Status status) {
this.status = status;
}

public int getPriority() {
return priority;
}

public void setPriority(int priority) {
this.priority = priority;
}

@Override
public String toString() {
return "Task [id=" + id + ", summary=" + summary + ", description=" + description + ", status=" + status
+ ", priority=" + priority + "]";
}

}

Write a converter main method
Write the following class to test the conversion.

package com.mycodetips.java.library.gson;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class MainTest {

public static void main(String[] args) {
List list = new ArrayList();
for (int i = 0; i < 20; i++) {
list.add(new Task(i, "Test1", "Test2", Task.Status.ASSIGNED, 10));
}
Gson gson = new Gson();
Type type = new TypeToken<List>() {}.getType();
String json = gson.toJson(list, type);
System.out.println(json);
List fromJson = gson.fromJson(json, type);

for (Task task : fromJson) {
System.out.println(task);
}
}
}

Exercise: Exclude a field from a Java object
The following is your data model.

package com.example.e4.rcp.todo.model;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Date;

public class Todo {

private PropertyChangeSupport changes = new PropertyChangeSupport(this);

public static final String FIELD_ID = "id";

public static final String FIELD_SUMMARY = "summary";

public static final String FIELD_DESCRIPTION = "description";

public static final String FIELD_DONE = "done";

public static final String FIELD_DUEDATE = "dueDate";

public final long id;
private String summary ="" ;
private String description ="";
private boolean done = false;
private Date dueDate;

public Todo(long i) {
id = i;
}

public Todo(long i, String summary, String description, boolean b, Date date) {
this.id = i;
this.summary = summary;
this.description = description;
this.done = b;
this.dueDate = date;
}

public long getId() {
return id;
}

public String getSummary() {
return summary;
}

public void setSummary(String summary) {
changes.firePropertyChange(FIELD_SUMMARY, this.summary,
this.summary = summary);
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
changes.firePropertyChange(FIELD_DESCRIPTION, this.description,
this.description = description);
}

public boolean isDone() {
return done;
}

public void setDone(boolean isDone) {
changes.firePropertyChange(FIELD_DONE, this.done, this.done = isDone);
}

public Date getDueDate() {
return dueDate;
}

public void setDueDate(Date dueDate) {
changes.firePropertyChange(FIELD_DUEDATE, this.dueDate,
this.dueDate = dueDate);
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Todo other = (Todo) obj;
if (id != other.id)
return false;
return true;
}

@Override
public String toString() {
return "Todo [id=" + id + ", summary=" + summary + "]";
}

public Todo copy() {
return new Todo(id, summary, description, done, dueDate);
}

public void addPropertyChangeListener(PropertyChangeListener l) {
changes.addPropertyChangeListener(l);
}

public void removePropertyChangeListener(PropertyChangeListener l) {
changes.removePropertyChangeListener(l);
}
}

Via the following class you can deserialize and serialize this data model into JSON and back to Java. In this example we exclude the field for the IPropertyChangeSupport.

package com.mycodetips.maven.lars;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class ExampleConvertor {

private static class MyCustomExclusionStrategy implements ExclusionStrategy {

public boolean shouldSkipClass(Class<?> arg0) {
return false;
}

public boolean shouldSkipField(FieldAttributes f) {
return (f.getDeclaringClass() == Todo.class && f.getName().equals("changes"));
}

}

private static int current;

public static void main(String[] args) {
List list = new ArrayList();
list.add(createTodo("Application model", "Flexible and extensible"));
list.add(createTodo("DI", "@Inject as programming mode"));
list.add(createTodo("OSGi", "Services"));
list.add(createTodo("SWT", "Widgets"));
list.add(createTodo("JFace", "Especially Viewers!"));
list.add(createTodo("CSS Styling", "Style your application"));
list.add(createTodo("Eclipse services", "Selection, model, Part"));
list.add(createTodo("Renderer", "Different UI toolkit"));
list.add(createTodo("Compatibility Layer", "Run Eclipse 3.x"));

// Add .excludeFieldsWithoutExposeAnnotation() to exclude fields not annotated with @Expose
Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(new MyCustomExclusionStrategy()).create();
Type type = new TypeToken<List>() {}.getType();
String json = gson.toJson(list, type);
try {
Files.write(Paths.get("db.txt"), json.getBytes(), StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
String content ="";
try {
content = new String(Files.readAllBytes(Paths.get("db.txt")));
} catch (IOException e) {
e.printStackTrace();
}

System.out.println(content);
}

private static Todo createTodo(String summary, String description) {
return new Todo(current++, summary, description, false, new Date());
}

}
  • Click to share on Reddit (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • More
  • Click to share on Pocket (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
Written by Ranjan - October 13, 2019 - 1523 Views
AUTHOR
Ranjan

This website is basically about of what we learnt from my years of experience as a software engineer on software development specifically on mobile application development, design patterns/architectures and its changing scenarios, security, troubleshooting, tools, tips&tricks and many more.

Next Post
Previous Post

Support us

Subscribe for updates

Join 8,278 other subscribers

Latest Posts

  • Exploring Single Point Failure
    Exploring Single Point Failures: Causes and Impacts
  • primitive-datatypes-new
    Exploring the Pros and Cons of Primitive Data Types
  • best practice clean code
    Essential Coding Standards and Best Practices for Clean Code
  • YT-Featured-Templates--lld
    What Business Problems Solves in Low Level Design (LLD)
  • SRP-SingleResopnsibility
    SRP : Single Responsibility Principle in Swift and Objective-C
whiteboard

Whiteboard(PRO)

whiteboard

Whiteboard(lite)

alphabets

Kids Alphabet

do2day

Do2Day

  • #about
  • #myapps
  • #contact
  • #privacy
  • #Advertise
  • #myQuestions

Android Database Interview IOS IOSQuestions Javascript Objective-c Programming Swift Tips&Tricks Web Wordpress

  • Exploring Single Point Failures: Causes and Impacts
  • Exploring the Pros and Cons of Primitive Data Types
  • Essential Coding Standards and Best Practices for Clean Code
MyCodeTips

©mycodetips.com

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.