I am trying to convert string into json array and the iterate over it.
String name = "lokesh";
String response = "[{"name":"lokesh"}, {"name":"cherukuri"}]";
JsonArray jsonArray = gson.fromJson(response, JsonArray.class);
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
System.out.println(jsonObject.get("name"));
if (jsonObject.get("name").toString().equals(name)) {
System.out.println("equal");
}
}
Problem: The If condition inside loop is not true because of quotes. because this line
System.out.println(jsonObject.get("name")); // printed "lokesh"
and System.out.println(name); //printed lokesh
Am i using GSON in a wrong way?
To get the value of the "name" attribute, you need to:
jsonObject.getString("name")
So, your code should be:
System.out.println(jsonObject.getString("name"));
if (jsonObject.getString("name").equals(name)) {
System.out.println("equal");
}
That's because jsonObject.get("name") return a JsonElement object. If you're sure it's an string, you can get the content by
jsonObject.get("name").getAsString()
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.