JSON strings to collection Java
-
21-12-2019 - |
Question
I have JSON string
For Example
[{
"id":"abc",
"name":"ffa",
"done":0
},
{
"id":"abc",
"name":"ffa",
"done":0
}]
I want to convert this JSON to collection of Examp class. I've tried use gson.
public static void main(String[] args)
{
Gson gson = new Gson();
Examp a=new Examp(); //Class Examp have 3 fields (id,name,done)
Examp b=new Examp();
a.done=0;
b.done=0;
a.id="foo";
b.id="foo1";
a.name="faa";
b.name="faa1";
ArrayList<Examp> arr= new ArrayList<Examp>();
arr.add(b);
arr.add(a);
String str = gson.toJson(arr);
System.out.println(str); //format check
ArrayList<Examp> collection = gson.fromJson(str, ArrayList.class);
}
At this moment the type of data in collection isn't Examp, but LinkedTreeMap. I have one question. How can I access this data (for example name)?
Solution
You need a TypeToken
ArrayList<Examp> collection = gson.fromJson(str, new TypeToken<ArrayList<Examp>>(){}.getType());
The TypeToken
is kind of a generic hack to get the generic type argument of a generic type use.
Note that you won't be able to use TypeToke
with type variables. (You'll be able to use it, but won't get what you want/expect).
OTHER TIPS
You need to use TypeToken
:
Type type = new TypeToken<ArrayList<Examp>>() {}.getType();
List<Examp> collection = gson.fromJson(json, type );
Reference on their wiki page:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow