Reputation: 1160
I am working on a REST application and the response I get from the server is a string of Json with the following format:
[{"car": "ford"}, {"car": "nissan"}, {"car": "bmw"}]
I want to use Gson to retrieve information by key through each element in that list, but because it is returned as a string I'm not sure how to go about it.
If I simply had the response be:
String json = {"car:": "ford"};
Then I could retrieve the car's value as follows:
Map<String,Object> result = new Gson().fromJson(json, Map.class);
System.out.println( result.get( "car" ) );
But because the original string is a list of json's it's more difficult.
Help appreciated. Ideally still using the Gson
class
Thanks
Upvotes: 0
Views: 59
Reputation: 4643
This will helps you:
public static void main(String[] args) {
JsonParser jsonParser = new JsonParser();
String log = "[{\"car\": \"ford\"}, {\"car\": \"nissan\"}, {\"car\": \"bmw\"}]";
JsonArray jsonObject = jsonParser.parse(log).getAsJsonArray();
for (JsonElement jsonElement : jsonObject)
System.out.println(jsonElement.getAsJsonObject().get("car").getAsString());
}
Upvotes: 1
Reputation: 2119
The json string you have is actually an array. Try below:
String json = "[{\"car\": \"ford\"}, {\"car\": \"nissan\"}, {\"car\": \"bmw\"}]";
List<Map<String,Object>> result = new Gson().fromJson(json, List.class);
result.forEach(l ->{
l.forEach((k, v)->{
System.out.println(k + ": " + v);
});
});
Upvotes: 0