使用到的类:net.sf.json.JSONObject
使用JSON时,除了要导入JSON网站上面下载的json-lib-2.2-jdk15.jar包之外,还必须有其它几个依赖包:commons-beanutils.jar,commons-httpclient.jar,commons-lang.jar,ezmorph.jar,morph-1.0.1.jar
下面是例子代码:
// JSON转换
JSONObject jsonObj = JSONObject.fromObject(jsonStrBody); //Json字符串 //jsonStrBody
Map classMap = new HashMap();
classMap.put("results", WeatherBean_Baidu_City.class);
// 将JSON转换成WeatherBean_Baidu
WeatherBean_Baidu weather = (WeatherBean_Baidu) JSONObject.toBean(jsonObj,
WeatherBean_Baidu.class, classMap);
System.out.println(weather.getResults());
*********************使用到的几个JAVA类实体代码******************************************
*********************WeatherBean_Baidu实体 类代码*********
package com.lenovo.conference.entity.vo;
import java.io.Serializable;
import java.util.List;
/**
* 天气Bean
*
* @author SHANHY
*
*/
@SuppressWarnings("serial")
public class WeatherBean_Baidu implements Serializable {
private String error;//错误号
private String status;//状态值
private String date;//日期
private List<WeatherBean_Baidu_City> results;//城市天气预报集合(因为一次可以查询多个城市)
public WeatherBean_Baidu() {
super();
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public List<WeatherBean_Baidu_City> getResults() {
return results;
}
public void setResults(List<WeatherBean_Baidu_City> results) {
this.results = results;
}
}
*********************WeatherBean_Baidu_City 实体 类代码*********
package com.lenovo.conference.entity.vo;
import java.io.Serializable;
import java.util.List;
/**
* 天气Bean
*
* @author SHANHY
*
*/
@SuppressWarnings("serial")
public class WeatherBean_Baidu_City implements Serializable {
private String currentCity;//城市名称
private String pm25;//pm2.5值
public WeatherBean_Baidu_City() {
super();
}
public String getCurrentCity() {
return currentCity;
}
public void setCurrentCity(String currentCity) {
this.currentCity = currentCity;
}
public String getPm25() {
return pm25;
}
public void setPm25(String pm25) {
this.pm25 = pm25;
}
}
*********************使用到的几个JAVA类实体代码******************************************
例子中解析所对应的JSON字符串
{"error":0,"status":"success","date":"2015-01-15",
"results":[
{"currentCity":"南京","pm25":"83"},
{"currentCity":"徐州","pm25":"154"}
]
}
//private List<WeatherBean_Baidu_City> results;
//private String currentCity;//城市名称
//private String pm25;//pm2.5值
---------------------
作者:catoop
来源:CSDN
原文:多级可以参考https://blog.csdn.net/catoop/article/details/42744705