0

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

1
  • Are all your keys car? If so, does using a map make sense? This looks much more like a list of objects to me with each object having a car field. Commented Dec 7, 2018 at 11:25

2 Answers 2

1

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

}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.