Classe usada: net.sf.json.jsonObject
Ao usar o JSON, além de importar o pacote JSON-LIB-2.2-JDK15.JAR baixado no site JSON, deve haver várias outras dependências: Commons-beanutils.Jar, Commons-httpclient.jar, Commons-Lang.jar, Ezmorph, Morph-1.0.1.jar
Aqui está o código de exemplo:
// JSON Conversão JsonObject jsonObj = jsonObject.FromObject (JSonstrbody); map <string, classe> classMap = new Hashmap <string, classe> (); classMap.put ("Results", WeatherBean_Baidu_City.Class); classe.put.put ("Index), WeatherBean_Baidu_City.Class); Classmap.put (" Index ", WeatherBean_Bean_Baidu_City.Class); Classmap.put (" Index ", WEATHERBEAN_BAN_BAIDU_CITY.CLASS); ClassMap.put ("Weather_Data", Weatherbean_baidu_city_weatherdata.class); // Converta JSON em Weatherbean_baidu Weatherbean_baidu Weather = (WeatherBean_Baidu) JsonObject.Tobean (JsonObj, Weatherbean_baidu.class, ClassMap); System.out.println (Weather.getResults ());Vários códigos de classe Java usados:
pacote com.lenovo.conference.entity.vo; importar java.io.serializable; importar java.util.list;/** * bean climático * * @author shanhy * */ @supressor; private; private (private privado "//rold strate; //rstrate; List <WeatherBean_Baidu_City> Resultados; // Conjunto de previsões climáticas da cidade (porque várias cidades podem ser consultadas imediatamente) public WeatherBean_Baidu () {super ();} public String getError () {Return Error;} public void setError (string) {this.error = Error;} string string; {this.status = status;} public string getDate () {date de retorno;} public void SetDate (string date) {this.date = date;} list public <weatherbean_baidu_city> getResults () {Resultados de retorno;} public void SetResults (listBean_Baid_Baid_BaDU_BADU () {Return; pacote com.lenovo.conference.entity.vo; importar java.io.serializable; importar java.util.list;/** * WeatherBean * * @author shanhy * */ @supressor stratetablenings ("serial") public class CaturyBean_Baidu_City implementa -se com strate5; List <WeatherBean_Baidu_City_Index> Index; // Set Expoponent Set List Private <Weatherbean_baidu_city_weatherdata> Weather_data; // Coleção climática de vários dias Public WeatherBean_Baidu_City () {Super ();} public string GetCurrentEntEntEntEn () {Currentity; {this.currentCity = currentCity;} public string getpm25 () {return pm25;} public void setpm25 (string pm25) {this.pm25 = pm25;} list public <WeatherBean_Baidu_City_City> lideIndex () {Return;}} {this.index = index;} lista pública <weatherbean_baidu_city_weatherdata> getweather_data () {return weather_data;} public void setweather_data (list <weatherbean_baidu_city_weatherdata> metethata_data) {this.weather_weather_weather_baid_city_city_weathata> weather_data) {th Thathata_weather_weather_baid_city_weathata> pacote com.lenovo.conference.entity.vo; importar java.io.Serializable;/** * Bean climático * * @author shanhy * */ @supressorwarnings ("serial") public cleterbean_baidu_city_weatherdata implementos string/{date strate; NightPictureUrl; // Weather Weather Private String Wind; // Direção do vento Temperatura da corda privada; // Temperatura public Weatherbean_baidu_city_weatherdata () {super ();} public string getDate () {date de retorno;} public void setDate (string) {this.date = date;} public string getStUtur; setDayPictureUrl (String DayPictureurl) {this.DayPictureurl = DayPictureurl;} public String getnnightPictureurl () {retorna NightPictureUrl;} public void SetnKenPictureurl (String NightPictureUrl) {this.nightPictUtUrl = NightPicturl; setWeather (clima da corda) {this.weather = clima;} public string getwind () {return wind;} public void setWind (string wind) {this.wind = wind;} public string getTemperature () {retorno temperatura;} public void Settemperature (temperatura da string) {this.temperaturesature =}; pacote com.lenovo.conference.entity.vo; importar java.io.serializable;/** * WeatherBean * * @author shanhy * */ @supressorwarnings ("serial") aula pública string; string straterbean_baidu_city_index implementos serializable {string string; string; // title string; public WeatherBean_Baidu_City_Index () {super ();} public String getTitle () {retorna title;} public void Settitle (string title) {this.title = title;} public string getzs () {return zs;} public voidzs (string zs) {this.zs () {return; Settipt (dica da string) {this.tip = tip;} public string getdes () {return des;} public void SetDes (string des) {this.des = des;}}No exemplo, analise a corda JSON correspondente
{"error":0,"status":"success","date":"2015-01-15","results":[{"currentCity":"Nanjing","pm25":"83","index":[{"title":"Clothes","zs":"Cooler","tipt":"Clothes index","des":"It is recommended to wear thick coats and sweaters. Old and weak As pessoas devem usar casacos, casacos e blusas de lã. "}, {" Title ":" Car Wash "," ZS ":" Mais adequado "," Tip ":" Índice de lavagem de carros "," des ":" Mais adequado para lavar carros, não haverá chuva no futuro e o vento é menos. "}, {" Title ":" Travel "," Zs ":" Supply "," Tips ":" Turismo "," Tip ":" Índice de Turismo "," Des ":" O tempo está melhor, a temperatura é ligeiramente menor, e não se sentirá um pouco legal, mas também é um bom tempo Than "," Tips ":" Índice de Cold "," Des ":" Todas as condições climáticas são adequadas, não há processo de resfriamento óbvio e a probabilidade de um resfriado é baixo. Se você insistir no exercício ao ar livre, escolha o exercício certo e mantenha -se aquecido. "}, {" title ":" UV Intensity "," Zs ":" Wintest "," Tip ":" UV Intensity Index "," Des ":" Winner UV Intensity Index "," Des ":" Por que o tempo da radiação UV não é necessário. Se você estiver ao ar livre por um longo tempo, é recomendável aplicar produtos de cuidados com o protetor solar com SPF entre 8 e 12. "}]," Weather_data ": [{" dat e ":" Quinta -feira 15 6 ℃), "DayPictureUrl": "http://api.map.baidu.com/images/weather/day/yin.png", "NightPictureurl": "http://api.map.baid.com/images/weather/night/night/duoyun.pnuen.pngu.ngaid..com/weather/weather/night/duoyun.pnuen.pngu brisa "," temperatura ":" 8 ~ 4 ℃ "}, {" Date ":" Friday "," DayPictureurl ":" http://api.map.baidu.com/images/weather/day/duoyun.png "," NightPictureurl ": http:/pi.map.baid.com/images/weatherl": http:/pi.map.baid.com/imageurl ": http:/pi.map.baid..images/images/weath/weath/weath/weath/weath/weathuatherl": " Sunny "," Wind ":" Northwest Wind Nível 3-4 "," Temperatura ":" 12 ~ 0℃"},{"date":"Saturday","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/qing.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/duoyun.png","weather":"Sunny to Cloudy "," Wind ":" Northeast Wind Nível 3-4 "," Temperatura ":" 8 ~ 0 ℃ "}, {" Date ":" Sunday "," DayPictureurl ":" http://api.map.baidu.com/images/weather/day/qing.png "," Nightp ictureurl ":" http://api.map.baidu.com/images/weather/night/night/qing.png "," Weather ":" Xing "," Wind ":" Western breeze","temperature":"10 ~ -1℃"}]},{"currentCity":"Xuzhou","pm25":"154","index":[{"title":"Clothes","zs":"Cooler","tip":"Clothes index","des":"It is recommended to wear thick coats, sweaters and other clothing. Pessoas velhas e fracas devem usar casacos, casacos de lã e blusas de lã. "}, {" title ":" lavagem de carros "," zs ":" mais adequado "," dica ":" índice de lavagem de carros "," des ":" mais adequado para lavar carros, não haverá chuva ou menos energia eólica no futuro. Um carro recém -esfregado pode ser mantido por pelo menos um dia. "}, {" title ":" Travel "," Zs ":" Suplementary "," Tip ":" Tourism Index "," Des ":" O tempo está melhor, mas não afetará seu humor ao viajar. A temperatura é adequada e a brisa é acompanhada, tornando -a adequada para viagens. "}, {" title ":" frio "," zs ":" fácil "," dica ":" O clima frio é mais provável de ocorrer, então adicione roupas adequadamente. Amigos com constituições fracas devem prestar atenção especial à proteção. "}, {" title ":" Exercício "," Zs ":" Não é adequado "," Tip ":" Sport Index "," Des ":" O tempo está melhor, mas considerando o clima frio, é recomendável que você pratique vários esportes internos. Se você se exercitar ao ar livre, preste atenção em manter o aquecimento e se preparar para as atividades. "}, {" title ":" UV Intensity "," Zs ":" Wintest "," Tip ":" UV Intensity Index "," Des ":" É um clima fraco da radiação UV e nenhuma proteção especial é necessária. Se você estiver ao ar livre por um longo tempo, é recomendável aplicar produtos de cuidados com o protetor solar com SPF entre 8 e 12. "}]," Weather_data ": [{" date ":" Quinta -feira 15 de janeiro (tempo real: 6℃)","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/duoyun.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/duoyun.png","weather":"cloudy","wind":"South Breeze "," Temperatura ":" 10 ~ 3 ℃ "}, {" Date ":" Friday "," DayPictureurl ":" http://api.map.baidu.com/images/weather/day/duoyun.png "," Nightp ictureurl ":" http://api.map.baidu.com/images/weather/night/night/duoyun.png "," Weather ":" Cloudy "," Wind ":" North Vento Nível 3-4 "," Temperatura ":" 11 ~ -4 ℃ "}, {" date ":" Saturday "," DayPictureurl ":" http://api.map.baidu.com/images/weather/day/duoyun.png "," Nigh tpictureurl ":" http://api.map.baidu.com/images/weather/night/duoyun.png "," clima ":" Cloudy "," Wind ":" East brisa do vento "," Temperatura ":" 6 ~ -4 ℃ "}, {" date ":" Sunday "," DayPictureurl ":" http://api.map.baidu.com/images/weather/day/duoyun.png "," Nightpi Ctureurl ":" http://api.map.baidu.com/images/weather/night/duoyun.png "," clima ":" Cloudy "," Wind ":" Westerly Nível de vento 3-4 "," Temperatura ":" 11 ~ -1 ℃ "}]}]}]}O método acima para converter strings JSON em objetos em Java (incluindo coleções de listas de várias camadas) é todo o conteúdo que compartilho com você. Espero que você possa lhe dar uma referência e espero que você possa apoiar mais o wulin.com.