1. 程式人生 > >java物件與json字串互轉

java物件與json字串互轉

場景:java物件與json字串互轉換
1.本例使用com.alibaba.fastjson.JSON類
2.實體物件轉換為json字串

public static String toJSONString(Object city) {
		String jsonStr = "";
		if (city != null) {
			jsonStr = JSON.toJSONString(city);
		}
		return jsonStr;
	}

3.json字串轉換為指定物件

public static <T> T parseObject(String text, Class<T> clazz) {
        return JSON.parseObject(text, clazz);
    }

4.實體物件示例

public class CityInfoModel implements Serializable {

	private static final long serialVersionUID = 4443714978780088961L;
	
	/** 城市名稱 */
	String cityName;
	/**城市面積*/ 
	double landArea;
	/**人口*/
	long population;
	/**生產總值*/
	double gross ;
	/** 行政區劃程式碼 */
	String areaNumber;
	/** 郵政編碼 */
	String postalCode;
	/** 電話區號 */
	String telephoneCode;
	/**車牌程式碼*/
	String carCode;
	/** 城市描述 */
	String cityDescribe;
	
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	public double getLandArea() {
		return landArea;
	}
	public void setLandArea(double landArea) {
		this.landArea = landArea;
	}
	public long getPopulation() {
		return population;
	}
	public void setPopulation(long population) {
		this.population = population;
	}
	public double getGross() {
		return gross;
	}
	public void setGross(double gross) {
		this.gross = gross;
	}
	public String getAreaNumber() {
		return areaNumber;
	}
	public void setAreaNumber(String areaNumber) {
		this.areaNumber = areaNumber;
	}
	public String getPostalCode() {
		return postalCode;
	}
	public void setPostalCode(String postalCode) {
		this.postalCode = postalCode;
	}
	public String getTelephoneCode() {
		return telephoneCode;
	}
	public void setTelephoneCode(String telephoneCode) {
		this.telephoneCode = telephoneCode;
	}
	public String getCarCode() {
		return carCode;
	}
	public void setCarCode(String carCode) {
		this.carCode = carCode;
	}
	public String getCityDescribe() {
		return cityDescribe;
	}
	public void setCityDescribe(String cityDescribe) {
		this.cityDescribe = cityDescribe;
	}
	@Override
	public String toString() {
		
		return "CityModel [cityName=" + cityName
				+",landArea=" + landArea
				+",population=" + population
				+",gross=" + gross
				+",areaNumber=" + areaNumber
				+",postalCode=" + postalCode
				+",telephoneCode=" + telephoneCode
				+",carCode=" + carCode
				+",cityDescribe=" + cityDescribe
				+"]";
	}
}

以上,TKS.