场景: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.