Skip to content

Instantly share code, notes, and snippets.

@raghothams
Created July 8, 2013 17:26
Show Gist options
  • Save raghothams/5950738 to your computer and use it in GitHub Desktop.
Save raghothams/5950738 to your computer and use it in GitHub Desktop.
Parse complex JSON string into Java objects using GSON
String jsonStr = "{ \"debug_info\" : [], \"html_attributions\" : [], \"results\" : [ { \"geometry\" : { \"location\" : { \"lat\" : 12.9774180, \"lng\" : 77.71423799999999 } }, \"icon\" : \"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png\", \"id\" : \"742446507e37ea90df8389717e4835fe659183ed\", \"name\" : \"The Oriental Pavilion\", \"reference\" : \"CoQBdAAAAO8vSS9emj1nHgkl6zfX2RBC2HqMJEUPMFHH3HkCxwNy4Sa8Y9CynZo7sozZV5CPEDMvvg5GMFQBPxAdPX0oDMzOJhvqDq_wr2eWIlFKV7fB2Inm1GWj0hCMOsLy3zD8RVAMN74JIsHyR-xQWulDRwsxxQ-bhbmBzCYFfxTKd-I1EhDBAkzm4xIWEEIdmWriBsgyGhStZUB2SzvEb2j6nuuzjsMxHHzNzg\", \"types\" : [ \"restaurant\", \"food\", \"establishment\" ], \"vicinity\" : \"134-136, Fortune Select Trinity, ITPL Main Road, EPIP Area, Whitefield, Bangalore\" }, { \"geometry\" : { \"location\" : { \"lat\" : 12.9786930, \"lng\" : 77.711260 } }, \"icon\" : \"http://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png\", \"id\" : \"5a63d9f23df7b22dc68480b43fd416dc9120471f\", \"name\" : \"Kerala Restaurant\", \"reference\" : \"CnRwAAAA6YNw-b9fOgYAtHMksU6juQSwok3-_KmWnpX1gZQCouCkDalEsoblw2rPmJ39E2v4o_gOORHuhX7rmiX93s-nonB27QAWcPjxq0Lb0mEHzNW1P3isxEhXZp9IjtA5JSqfAm1rvLfaoS0q5LJ4KljY_hIQ8h6Eq6NarZrK8IpgfAUq1RoUY2g1OixL5PDk-IoHKO0zuhHObzw\", \"types\" : [ \"restaurant\", \"food\", \"establishment\" ], \"vicinity\" : \"KIADB Export Promotion Industrial Area, Whitefield, Bangalore\" } ], \"status\" : \"OK\" }";
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(jsonReader).getAsJsonObject();
JsonArray resultArray = jsonObj.get("results");
ArrayList<ResultTemplate> parsedResultList = new ArrayList<ResultTemplate>();
Iterator it = resultArray.iterator();
while(it.hasNext()){
JsonElement elem = it.next();
try{
//Parse the important element into whatever structure you're creating
Gson gson = new Gson();
Object object = gson.fromJson(jsonStr,ResultTemplate.class);
parsedTemplate.add(object);
} catch(Exception e){
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment