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.
- package json;
- import com.google.gson.Gson;
- import com.google.gson.JsonElement;
- public class JSONParsing {
- public static void main(String[] args) {
- Gson gson = new com.google.gson.Gson();
- String json = "{\"city\": \"NewYork\", \"zip\": \"l2345\", \"timeZone\":\"EST\", \"Country\": \"USA\", \"population\":632541,"
- + " \"month\": September,\"year\":\"2015\"}";
- System.out.println("Original Object:\n"+json+"\n");
- com.google.gson.JsonObject result = gson.fromJson(json,
- JsonElement.class).getAsJsonObject();
- System.out.println("JsonObject Object:\n"+result.toString());
- System.out.println();
- System.out.println("\nGetting specific element:zip:"
- + result.get("zip"));
- City city = new City();
- city.setName(result.get("city").getAsString());
- city.setPopulation(result.get("population").getAsLong());
- System.out.println("\n"+city.toString());
- }
- }
- class City {
- private String name;
- private Long population;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Long getPopulation() {
- return population;
- }
- public void setPopulation(Long population) {
- this.population = population;
- }
- @Override
- public String toString() {
- return "City [name=" + name + ", population=" + population + "]";
- }
- }
Comments
Post a Comment