Gson to convert Java Object to/from Json

The tutorial guides you how to convert Java Object to Json and vice-versa by Gson.

Related Articles:
Jackson to convert Java Object to/from Json String
How to convert Java Object into/from XML – with Castor & Spring Boot

A. Concepts

2 important concepts need introduce: json & gson

I. Json

– JSON: JavaScript Object Notation.
– A lightweight data-interchange format.
– It is easy for machines to parse and generate.
– JSON is a text format that is completely language independent

II. Gson library

Gson is a Java library for converting Java Objects into their JSON. Provide 2 methods: toJson() and fromJson() methods to convert Java objects to JSON and vice-versa.

B. Practice

I. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE (It’s OK if you use Eclipse)

II. Overview
1. Project Structure

structure of gson project

2. Step to do

– Create Maven project
– Add Gson dependency
– Create Java Model class
– Use Gson functions for converting
– Run and check result

III. Practice
1. Create Maven project

Open Spring Tool Suite, on main menu, choose File->New->Maven Project, check Create a simple project, Press Next, add project info then press Finish, a Maven project is created.

2. Add Gson dependency

Open pom.xml file, add Gson dependency:

3. Create Java Model class

Create a Employee model class:

4. Use Gson functions for converting

– Convert Java Object to Json by toJson funtion of GSON:

– Convert Json to Java Object:

5. Run & Check result

– Main class:

– Run with result:

III. Source code


By grokonez | December 8, 2016.

Last updated on June 4, 2017.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *