Using GSON to Parse JSON in Java

The following is a video and the program to understand the how JSON can be Parsed  in Java using Gson library from Google.

Here is the entire program:
  1. package json;
  2. import com.google.gson.Gson;
  3. import com.google.gson.JsonElement;
  4. public class JSONParsing {
  5. public static void main(String[] args) {
  6. Gson gson = new com.google.gson.Gson();
  7. String json = "{\"city\": \"NewYork\", \"zip\": \"l2345\", \"timeZone\":\"EST\", \"Country\": \"USA\", \"population\":632541,"
  8. + " \"month\": September,\"year\":\"2015\"}";
  9. System.out.println("Original Object:\n"+json+"\n");
  10. com.google.gson.JsonObject result = gson.fromJson(json,
  11. JsonElement.class).getAsJsonObject();
  12. System.out.println("JsonObject Object:\n"+result.toString());
  13. System.out.println();
  14. System.out.println("\nGetting specific element:zip:"
  15. + result.get("zip"));
  16. City city = new City();
  17. city.setName(result.get("city").getAsString());
  18. city.setPopulation(result.get("population").getAsLong());
  19. System.out.println("\n"+city.toString());
  20. }
  21. }
  22. class City {
  23. private String name;
  24. private Long population;
  25. public String getName() {
  26. return name;
  27. }
  28. public void setName(String name) {
  29. this.name = name;
  30. }
  31. public Long getPopulation() {
  32. return population;
  33. }
  34. public void setPopulation(Long population) {
  35. this.population = population;
  36. }
  37. @Override
  38. public String toString() {
  39. return "City [name=" + name + ", population=" + population + "]";
  40. }
  41. }

Comments

Popular posts from this blog

Java Interview : Threads

Spring Framework Interview Notes : Part Two Wiring

Card Dealer In Java in Less than 5 minutes