How to deserialize a list using GSON or another JSON library in Java?
With Gson, you'd just need to do something like:
List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());
You might also need to provide a no-arg constructor on the Video
class you're deserializing to.
Deserialize a ListT object with Gson?
Method to deserialize generic collection:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
...
Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);
Since several people in the comments have mentioned it, here's an explanation of how the TypeToken
class is being used. The construction new TypeToken<...>() {}.getType()
captures a compile-time type (between the <
and >
) into a runtime java.lang.reflect.Type
object. Unlike a Class
object, which can only represent a raw (erased) type, the Type
object can represent any type in the Java language, including a parameterized instantiation of a generic type.
The TypeToken
class itself does not have a public constructor, because you're not supposed to construct it directly. Instead, you always construct an anonymous subclass (hence the {}
, which is a necessary part of this expression).
Due to type erasure, the TypeToken
class is only able to capture types that are fully known at compile time. (That is, you can't do new TypeToken<List<T>>() {}.getType()
for a type parameter T
.)
For more information, see the documentation for the TypeToken
class.
Deserializing list with GSON
Try this -
AllEntity.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AllEntity {
@SerializedName("kbIdentifier")
@Expose
private String kbIdentifier;
@SerializedName("disambiguationScore")
@Expose
private String disambiguationScore;
public String getKbIdentifier() {
return kbIdentifier;
}
public void setKbIdentifier(String kbIdentifier) {
this.kbIdentifier = kbIdentifier;
}
public String getDisambiguationScore() {
return disambiguationScore;
}
public void setDisambiguationScore(String disambiguationScore) {
this.disambiguationScore = disambiguationScore;
}
@Override
public String toString() {
return "AllEntity [kbIdentifier=" + kbIdentifier
+ ", disambiguationScore=" + disambiguationScore + "]";
}
}
BestEntity.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BestEntity {
@SerializedName("kbIdentifier")
@Expose
private String kbIdentifier;
@SerializedName("disambiguationScore")
@Expose
private String disambiguationScore;
public String getKbIdentifier() {
return kbIdentifier;
}
public void setKbIdentifier(String kbIdentifier) {
this.kbIdentifier = kbIdentifier;
}
public String getDisambiguationScore() {
return disambiguationScore;
}
public void setDisambiguationScore(String disambiguationScore) {
this.disambiguationScore = disambiguationScore;
}
@Override
public String toString() {
return "BestEntity [kbIdentifier=" + kbIdentifier
+ ", disambiguationScore=" + disambiguationScore + "]";
}
}
Mention.java
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Mention {
@SerializedName("allEntities")
@Expose
private List<AllEntity> allEntities = new ArrayList<AllEntity>();
@SerializedName("name")
@Expose
private String name;
@SerializedName("bestEntity")
@Expose
private BestEntity bestEntity;
public List<AllEntity> getAllEntities() {
return allEntities;
}
public void setAllEntities(List<AllEntity> allEntities) {
this.allEntities = allEntities;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BestEntity getBestEntity() {
return bestEntity;
}
public void setBestEntity(BestEntity bestEntity) {
this.bestEntity = bestEntity;
}
@Override
public String toString() {
return "Mention [allEntities=" + allEntities + ", name=" + name
+ ", bestEntity=" + bestEntity + "]";
}
}
Main.java
import com.example.ElemntList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
/**
* @param args
*/
public static void main(String[] args) {
String s = "{\"mentions\":[{\"allEntities\":[{\"kbIdentifier\":\"YAGO:Bob_Dylan\",\"disambiguationScore\":\"0.63692\"}],\"name\":\"Dylan\",\"bestEntity\":{\"kbIdentifier\":\"YAGO:Bob_Dylan\",\"disambiguationScore\":\"0.63692\"}},{\"name\":\"Duluth\",\"bestEntity\":{\"kbIdentifier\":\"YAGO:Duluth\\u002c_Minnesota\",\"disambiguationScore\":\"0.63149\"}}]}";
ElemntList info = gson.fromJson(s, ElemntList.class);
System.out.println(info);
}
}
Result is -
ElemntList [mentions=[Mention [allEntities=[AllEntity [kbIdentifier=YAGO:Bob_Dylan, disambiguationScore=0.63692]], name=Dylan, bestEntity=BestEntity [kbIdentifier=YAGO:Bob_Dylan, disambiguationScore=0.63692]], Mention [allEntities=[], name=Duluth, bestEntity=BestEntity [kbIdentifier=YAGO:Duluth,_Minnesota, disambiguationScore=0.63149]]]]
Unable to deserialize the list of object data using GSON library
- Why JsonProperty instead of SerializableName? Are you mixing Jackson and Gson?
- What is the output of ser.getKeywordStats()?
Because I have tested your code by hardcoding that json-string instead of ser.getKeywordStats(), and it worked without any issue.
Deserialise a generic list in Gson
There is no way to do it without passing actual type of T
(as Class<T>
) to your method.
But if you pass it explicitly, you can create a TypeToken
for List<T>
as follows:
private <T> List<T> GetListFromFile(String filename, Class<T> elementType) {
...
TypeToken<ArrayList<T>> token = new TypeToken<ArrayList<T>>() {};
List<T> something = gson.fromJson(data, token.getType());
...
}
See also:
TypeToken
How to deserialize JSON string between JSON.org library using GSON library
Just make keywords and countries a java List type. I've never seen org.json mixed with gson. Usually gson replaces org.json it's not meant to be used together.
EDIT:
Small example:
class Example {
private String name;
private Integer age;
private List<String> keywords;
private List<String> countries;
public String toString() {
return new Gson().toJson(this);
}
}
Trouble deserializing JSON into Java objects with GSON
The JSON you are deserializing represents an object with a list of objects on it. The Java object you are trying to deserialize to needs to match that.
First, create a new class MovieList
.
class MovieList {
List<Movie> movies;
}
Update your Movies
class to be called Movie
, since it represents a single movie.
class Movie {
String name;
String url;
String IMAX;
String rating;
List<Cast> cast;
}
Now try calling gson.fromJson(...)
with the following
MovieList movieList = gson.fromJson(new FileReader("src/main/input.json"), MovieList.class);
System.out.println(movieList.getMovies().get(0));
Related Topics
Setting Jvm/Jre to Use Windows Proxy Automatically
Does Java Se 8 Have Pairs or Tuples
Use a .Jar Java Library API in C#
Threads Configuration Based on No. of Cpu-Cores
How to Pass C Structs Back and Forth to Java Code in Jni
Differencebetween Bounded Wildcard and Type Parameters
Howto Get Rid of <Mvc:Annotation-Driven />
Does Java Read Integers in Little Endian or Big Endian
Using a Prepared Statement and Variable Bind Order by in Java with Jdbc Driver
Spring Cache with Collection of Items/Entities
How Does the Jvm Ensure That System.Identityhashcode() Will Never Change
What Is the Idiomatic Way to Compose a Url or Uri in Java
Is It Bad Practice to Use Reflection in Unit Testing
How to Improve the Performance of G.Drawimage() Method for Resizing Images
How to Run Ssh Commands on Remote System Using Java