Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

package org.arpit.java2blog;

public class Country {
	int id;
	String countryName;
	long population;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCountryName() {
		return countryName;
	}
	public void setCountryName(String countryName) {
		this.countryName = countryName;
	}
	public long getPopulation() {
		return population;
	}
	public void setPopulation(long population) {
		this.population = population;
	}
	@Override
	public String toString() {
		return "Country [id=" + id + ", countryName=" + countryName + ", population=" + population + "]";
	}
}

Create a class named “SimpleGsonMain”

package org.arpit.java2blog;

import com.google.gson.Gson;

public class SimpleGsonMain {

	public static void main(String[] args) {
		String jsonString="{'id'=1,countryNasme='India',population=20000}";
		
		Gson gson=new Gson();
		Country country=gson.fromJson(jsonString, Country.class);
		System.out.println(country.toString());
	}

}

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.

[
   {
      "id":1,
      "countryName":"India",
      "population":20000
   },
   {
      "id":2,
      "countryName":"Nepal",
      "population":12000
   },
   {
      "id":3,
      "countryName":"Bhutan",
      "population":6000
   },
   {
      "id":4,
      "countryName":"China",
      "population":30000
   }
]

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

List listOfCountries=gson.fromJson(jsonString, ArrayList.class);

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.

package org.arpit.java2blog;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.util.List;

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

public class GsonReadFileToListMain {

	public static void main(String[] args) {
		Reader reader;
		try {
			reader = new FileReader("/Users/apple/Desktop/Countries.json");
			Gson gson=new Gson();
			// Usinf fromJson(reader,type)
			List countryList=gson.fromJson(reader,new TypeToken>(){}.getType());
			
			System.out.println("=======================");
			System.out.println("List of Countries are:");
			System.out.println("=======================");
			for (Country country : countryList) {
				System.out.println(country);
			}
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

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:

package org.arpit.java2blog;

import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GsonFromJsonToMapMain {
	public static void main(String args[])
	{
		Gson gson=new Gson();
		String counrtyCapitalJson="{'India':'Delhi','Nepal':'Kathmandu','China':'Beijing','Bhutan':'Thimphu'}";
		Map map=gson.fromJson(counrtyCapitalJson,new TypeToken>(){}.getType());
		for(String key:map.keySet())
		{
			System.out.println(map.get(key)+" is capital of "+key);
		}
	}
}

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.

The post Gson fromJson example appeared first on Java2Blog.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

Gson fromJson example

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×