Reputation: 275
I'm trying to parse a string representation of a JSON object into a List of maps. The json object will be structured something like the following:
[
{
"first_name": "fname1",
"last_name": "lname1"
},
{
"first_name": "fname2",
"last_name": "lname2"
}
.
.
.
]
The only thing that is known is the strings values (e.g "first_name", "last_name") on runtime only, therefore I cannot create any predefined classes (like usually used in fromJson() method).
I have tried to create the following function (after I saw some examples online) and it didn't work:
public List<Map<String, Object>> fromJson(String jsonAsString) {
final JsonElement jsonElement = this.jsonParser.parse(jsonAsString);
List<Map<String, Object>> myList= new ArrayList<Map<String, Object>>();
Type listType = TypeToken.get(myList.getClass()).getType();
myList= (new Gson()).fromJson(jsonElement, listType);
return myList;
}
The result of this function is a list (length == 2 in the above case) but instead of 2 maps i'm getting 2 Objects.
Any help? Thanks!
Upvotes: 2
Views: 11613
Reputation: 242686
I don't quite understand your use of TypeToken
.
The point of TypeToken
is to capture parameterized type (such as List<...>
) by creating anonymous class that extends generic supertype parameterized by the type you want to capture, using the following syntax:
new TypeToken<... type you want to capture ...>() {}.getType()
In your case it should be used as follows:
myList = new Gson().fromJson(jsonAsString,
new TypeToken<List<Map<String, Object>>>() {}.getType());
Upvotes: 3
Reputation: 2786
You cannot use generics like that, at runtime List<Map<String, Object>> myList
is the same as List<Object> myList
.
You can try with an array of maps
Gson gson = new Gson();
Map[] x = new Map[0];
Map[] fromJson = gson.fromJson("[\r\n" +
" { \r\n" +
" \"first_name\": \"fname1\",\r\n" +
" \"last_name\": \"lname1\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"first_name\": \"fname2\",\r\n" +
" \"last_name\": \"lname2\"\r\n" +
" }]",x.getClass());
Upvotes: 0