Type itemsMapType = new TypeToken<Map<Integer, GoodsItem>>() {}.getType(); Type itemsListType = new TypeToken<List<GoodsItem>>() {}.getType(); Type itemsArrType = new TypeToken<GoodsItem[]>() {}.getType();
public class GoodsItem{ String name; float price; public GoodsItem(String name, float price) { this.name = name; this.price = price; public String toString(){ return name + " : " + price; } }
Map<Integer, GoodsItem> mapItems = new HashMap<Integer, GoodsItem>(); mapItems.put(1, new GoodsItem("Samsung", 51200.6f)); mapItems.put(2, new GoodsItem("Lg", 5400.6f)); mapItems.put(3, new GoodsItem("Alcatel", 4500.6f)); String jsonStr = new Gson().toJson(mapItems); System.out.println(jsonStr);
{ "1":{"name":"Samsung","price":51200.6}, "2":{"name":"Lg","price":5400.6}, "3":{"name":"Alcatel","price":4500.6} }
Map<Integer, GoodsItem> mapItemsDes = new Gson().fromJson(jsonStr, itemsMapType); System.out.println(mapItemsDes.toString());
{1=Samsung : 51200.6, 2=Lg : 5400.6, 3=Alcatel : 4500.6}
List<GoodsItem> listItems = new ArrayList<GoodsItem>(); listItems.add( new GoodsItem("Samsung" , 51200.6f)); listItems.add( new GoodsItem("Lg" , 5400.6f)); listItems.add( new GoodsItem("Alcatel" , 4500.6f)); String jsonStr = new Gson().toJson(listItems); System.out.println(jsonStr);
[ {"name":"Samsung","price":51200.6}, {"name":"Lg","price":5400.6}, {"name":"Alcatel","price":4500.6} ]
List<GoodsItem> listItemsDes = new Gson().fromJson(jsonStr,itemsListType); System.out.println(listItemsDes.toString());
[Samsung : 51200.6, Lg : 5400.6, Alcatel : 4500.6]
GoodsItem[] arrItems = new GoodsItem[3]; arrItems[0] = new GoodsItem("Samsung", 51200.6f); arrItems[1] = new GoodsItem("Lg", 5400.6f); arrItems[2] = new GoodsItem("Alcatel", 4500.6f); String jsonStr = new Gson().toJson(arrItems); System.out.println(jsonStr);
[ {"name":"Samsung","price":51200.6}, {"name":"Lg","price":5400.6}, {"name":"Alcatel","price":4500.6} ]
GoodsItem[] arrItemsDes = new Gson().fromJson(jsonStr, itemsArrType); System.out.println(Arrays.toString(arrItemsDes));
[Samsung : 51200.6, Lg : 5400.6, Alcatel : 4500.6]
public class GoodsItem implements Parcelable { String name; float price; public GoodsItem(String name, float price) { this.name = name; this.price = price; public String toString(){ return name + " : " + price; } protected GoodsItem(Parcel in) { name = in.readString(); price = in.readFloat(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeFloat(price); } @SuppressWarnings("unused") public static final Parcelable.Creator<GoodsItem> CREATOR = new Parcelable.Creator<GoodsItem>() { @Override public GoodsItem createFromParcel(Parcel in) { return new GoodsItem(in); } @Override public GoodsItem[] newArray(int size) { return new GoodsItem[size]; } }; }
Source: https://habr.com/ru/post/253266/
All Articles