First Create Bean Class that you need to convert on ArrayList. Right now for sample i have just create country Class as below.
public class Country {
private int countryID;
private String countryName;
public Country(int countryID, String countryName) {
this.countryID = countryID;
this.countryName = countryName;
}
public int getCountryID() {
return countryID;
}
public void setCountryID(int countryID) {
this.countryID = countryID;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
Now lets Create Json String for convert Java ArrayList Object. This string also come from JSON API.
private String countryJson = "{\"category\": [{\n" +
" \"countryID\":\"1\",\n" +
" \"countryName\": \"India\",\n" +
" {\n" +
" \"countryID\": \"2\",\n" +
" \"countryName\": \"UK\",\n" +
" },\n" +
" {\n" +
" \"countryID\": \"3\",\n" +
" \"countryName\": \"US\",\n" +
" \n" +
" }\n" +
" ]\n" +
" }";
Type listType = new TypeToken>() {}.getType();
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(countryJson);
JsonArray jsonArr = jo.getAsJsonArray("category");
Gson googleJson = new Gson();
countries = googleJson.fromJson(jsonArr.toString(), listType);
System.out.println("List Elements are : "+countries.get(0).getCountryName());
That's it.
No comments:
Post a Comment