1. 程式人生 > >Gson實現json資料與物件, 集合之間的轉換

Gson實現json資料與物件, 集合之間的轉換

Gson是谷歌開源的用於處理json格式資料的工具.

使用Gson需要引入第三方jar包:

package Exercise1_gson;

import java.io.Serializable;
/**
 * @author huangxinyi
 * 實體類product
 * 
 */
public class Product implements Serializable {
	
	private static final long serialVersionUID = -899351582186856010L;
	private String brand;
	private String type;
	private String color;
	private float price;
	
	public Product(){}
	
	public Product(String brand, String type, String color, float price) {
		this.brand = brand;
		this.type = type;
		this.color = color;
		this.price = price;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((brand == null) ? 0 : brand.hashCode());
		result = prime * result + ((color == null) ? 0 : color.hashCode());
		result = prime * result + Float.floatToIntBits(price);
		result = prime * result + ((type == null) ? 0 : type.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Product other = (Product) obj;
		if (brand == null) {
			if (other.brand != null)
				return false;
		} else if (!brand.equals(other.brand))
			return false;
		if (color == null) {
			if (other.color != null)
				return false;
		} else if (!color.equals(other.color))
			return false;
		if (Float.floatToIntBits(price) != Float.floatToIntBits(other.price))
			return false;
		if (type == null) {
			if (other.type != null)
				return false;
		} else if (!type.equals(other.type))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Product [brand=" + brand + ", type=" + type + ", color=" + color + ", price=" + price + "]";
	}
	
	
}
 
 

package Exercise1_gson;

import java.util.ArrayList;

import java.util.List;

import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;

/**

* @author huangxinyi

* 測試類

*/

public class Test {    

    private Gson gson = new Gson();

    private static ArrayList<Product> plist = new ArrayList<>();

 

    @org.junit.Test

    public void test() {

        String jsonArr = "[{\"brand\":\"聯想\",\"type\":\"電腦\",\"color\":\"白色\",\"price\":\"3000\"},"+

                         "{\"brand\":\"小米\",\"type\":\"手機\",\"color\":\"黑色\",\"price\":\"2500\"},"+

                         "{\"brand\":\"華為\",\"type\":\"手機\",\"color\":\"白色\",\"price\":\"2000\"},"+

                         "{\"brand\":\"戴爾\",\"type\":\"電腦\",\"color\":\"藍色\",\"price\":\"4000\"},"+

                         "{\"brand\":\"蘋果\",\"type\":\"手機\",\"color\":\"紅色\",\"price\":\"5000\"}]";

 

        String jsonStr = "{\"brand\":\"聯想\",\"type\":\"電腦\",\"color\":\"白色\",\"price\":\"3000\"}";

        System.out.println("json轉物件:" + jsonToObj(jsonStr));    

   

        Product product = new Product("華為","手機","黑色",2000);       

        System.out.println("物件轉json:" + objToJson(product));

 

        System.out.println("json轉集合:" + jsonToList(jsonArr));        

        System.out.println("集合轉json:" + listToJson(jsonToList(jsonArr)));

    }

        // 物件轉json

        private String objToJson(Object o){

            return gson.toJson(o);

        }

        // json轉物件

        private Object jsonToObj(String json){

            return gson.fromJson(json, Object.class);

        }

        // 將json轉集合

        private ArrayList<Product> jsonToList(String jsonArr){

            plist = gson.fromJson(jsonArr, new TypeToken<ArrayList<Product>>(){}.getType());return plist;

        }

    

        // 集合轉json

        private String listToJson(List<Product> list){

            return gson.toJson(list);

        }

}