简体   繁体   中英

Parse list of json string using GSON

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

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());

}

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);
    });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM