Google Gson for converting Java object to / from JSON
Following code snippet shows how you can convert Java object to JSON string and vice versa.
Source code (Item.java)
Source code (ObjectToJSON.java)
Output
Source code (JSONToObject.java)
Output
Source code (Item.java)
public class Item { private Long id; private String name; private Double price; public Item() { } public Item(String name, Double price) { this.name = name; this.price = price; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public String toString() { return "Item{" + "name=" + name + ", price=" + price + '}'; } }
Source code (ObjectToJSON.java)
import com.google.gson.Gson; import com.javaquery.bean.Item; import java.util.Arrays; import java.util.List; /** * Convert Java object to json using gson. * @author javaQuery * @date 24th March, 2017 * @Github: https://github.com/javaquery/Examples */ public class ObjectToJSON { public static void main(String[] args) { /* Java object */ Item iPhone = new Item("iPhone 7", 100.12); Item blackBerry = new Item("Black Berry", 50.12); List<Item> items = Arrays.asList(iPhone, blackBerry); Gson gson = new Gson(); /* Convert single Object to JSON */ String jsonObjectString = gson.toJson(iPhone); System.out.println(jsonObjectString); /* Convert List of Object to JSON */ String jsonArrayString = gson.toJson(items); System.out.println(jsonArrayString); } }
Output
{"name":"iPhone 7","price":100.12} [{"name":"iPhone 7","price":100.12},{"name":"Black Berry","price":50.12}]
Source code (JSONToObject.java)
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.javaquery.bean.Item; import java.lang.reflect.Type; import java.util.List; /** * Convert json string to java object using gson. * @author javaQuery * @date 24th March, 2017 * @Github: https://github.com/javaquery/Examples */ public class JSONToObject { public static void main(String[] args) { String jsonObjectString = "{\"name\":\"iPhone 7\",\"price\":100.12}"; String jsonArrayString = "[{\"name\":\"iPhone 7\",\"price\":100.12},{\"name\":\"Black Berry\",\"price\":50.12}]"; Gson gson = new Gson(); /* Convert JSONObject String to Object */ Item item = gson.fromJson(jsonObjectString, Item.class); System.out.println(item); /* Convert JSONArray String to Object */ Type type = new TypeToken<List<Item>>(){}.getType(); List<Item> items = gson.fromJson(jsonArrayString, type); System.out.println(items); } }
Output
Item{name=iPhone 7, price=100.12} [Item{name=iPhone 7, price=100.12}, Item{name=Black Berry, price=50.12}]
0 comments :