Gson fromJson example


In this post, we will see about Gson fromJson example.We have already seen simple Gson example in the previous post.

Gson fromJson method is used to convert JSON String or JsonObject or Reader to the corresponding object. You can read about various variants about fromJson method over Gson page.

I will demonstrate Gson fromJson method with help of example.

Read simple JSON String

You can use fromJson(String json, Class classOfT) method to read simple Json string.
Let’s say you have Country class as below.

Create a class named “SimpleGsonMain”

When you run above program, you will get below output.

Country [id=1, countryName=null, population=20000]

Read JSON Array to List

Let’s say you need to read below JSON string from file.

We need to convert above JSON Array to List<Country>
You won’t be simply able to do it using below code.

Above code won’t work. If object is ParameterizedType type, then you need to use type to convert it.
Hence, you can use fromJson(Reader json, Type typeOfT) to read above json file.

When you run above program, you will get below output:

List of Countries are:
Country [id=1, countryName=India, population=20000]
Country [id=2, countryName=Nepal, population=12000]
Country [id=3, countryName=Bhutan, population=6000]
Country [id=4, countryName=China, population=30000]

Read Json String and convert it to Map

Let’s say we have flat gson string and we want to put it in a Map. You can simply use fromJson(String json, Type typeOfT) and convert String to Map as below:

When you run above program, you will get below output:

Delhi is capital of India
Kathmandu is capital of Nepal
Beijing is capital of China
Thimphu is capital of Bhutan

As you can see we have provided TypeToken to convert it specific type.

That’s all about Gson fromJson example.


Add Comment