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.
You can use fromJson(String json, Class classOfT) method to read simple Json string.
Let’s say you have Country class as below.
Let’s say you need to read below JSON string from file.
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.
As you can see we have provided TypeToken to convert it specific type.
That’s all about Gson fromJson example.