一.JSON格式以及JSON数据字符的解析方式
首先,我们需要知道JSON的格式。那么JSON的格式是怎么样的呢?
{
“name”:“JY”,
“age”:22
}
这就是一个最简单的JSON格式例子。JOSN格式采用的是key:value的键值相对应来写的,key是字符串,value为key的值,它有String,number,boolean,array等类型。key之间用“,”来隔开。
JAVA中传统解析JSON一般有三种方式:
首先你的生成一个JSON字符串,你可以这样生成
public static String createJsonString(String key, Object value) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
将JSON数据生成为
1.一个JavaBean,
2.一个List数组,
3.一个嵌套Map的List数组
在这里我推荐使用第一种方式(生成为一个JavaBean),因为在项目中一般需要对JSON数据中的key的value做一些处理,这时候JavaBean的好处就体现出来了,它相对于其他两种方式的使用更加灵活。
二.JSON之GSON
在android studio中有一个十分好用的插件,就是GsonFormat,它可以很方便的帮助我们将JSON数据字符串自动生成为一个JavaBean,用Gson来解析就很容易了。
当你在android studio安装好GsonFormat之后,使用步骤如下:
1.在Code中选中Generate
2.选中
3.将你获取到的JSON数据直接复制到里面去就可以一键生成你所需要的JavaBean
好,基础已经讲完。下面讲讲如何获取天气的JSON数据
三、接入和风天气api的天气预报demo
若想接入api,就需要一个app的key,这时候我们需要到和风天气的官网去注册一个账号,一般我们选个人开发者就好了,免费的api也算够我们测试使用。当然,如果你是公司项目使用需要更多的数据,你可以选择企业客户注册。
注册完成认证通过后你需要去控制台找到自己的认证key,因为api接入的参数中需要这个key
那么,我们应该怎么接入呢?别急嘛,人家有接入文档的嘛!
箭头所指的地方就是接入api的方式,parameters在下面有说明,自己可以根据自己的需要来接入,但是一定要有key
在这里,你可以将这个请求地址直接输入到浏览器中查看请求到的JSON数据是什么。不过,个人推荐使用postman来查看,因为不需要自己改格式,自动生成自己想要的格式,有没有觉得好方便。
好,直到现在,我们已经获取到我们需要的和风天气的JSON数据了,接下来就是如何在demo中将它生成为一个JavaBean以及解析它们了。
还记得我们前面说的android studio的插件GsonFormat嘛,对,没错,现在就是使用它的时候了.由于我当时是请求所有的免费天气api,所以代码很多很长,不过没关系,因为都不需要你去写这个代码,毕竟一键生成嘛,会用就行,对吧。
public class WeatherBean {
private List HeWeather6;
public List getHeWeather6() {
return HeWeather6;
}
public void setHeWeather6(List HeWeather6) {
this.HeWeather6 = HeWeather6;
}
public static class HeWeather6Bean {
/**
* basic : {"cid":"CN101010100","location":"北京","parent_city":"北京","admin_area":"北京","cnty":"中国","lat":"39.90498734","lon":"116.4052887","tz":"+8.00"}
* update : {"loc":"2018-05-01 14:47","utc":"2018-05-01 06:47"}
* status : ok
* now : {"cloud":"0","cond_code":"504","cond_txt":"浮尘","fl":"18","hum":"26","pcpn":"0.0","pres":"1013","tmp":"21","vis":"10","wind_deg":"72","wind_dir":"东北风","wind_sc":"3","wind_spd":"14"}
* daily_forecast : [{"cond_code_d":"504","cond_code_n":"101","cond_txt_d":"浮尘","cond_txt_n":"多云","date":"2018-05-01","hum":"35","mr":"20:19","ms":"06:13","pcpn":"0.0","pop":"0","pres":"1015","sr":"05:16","ss":"19:09","tmp_max":"24","tmp_min":"13","uv_index":"6","vis":"20","wind_deg":"3","wind_dir":"北风","wind_sc":"4-5","wind_spd":"33"},{"cond_code_d":"101","cond_code_n":"100","cond_txt_d":"多云","cond_txt_n":"晴","date":"2018-05-02","hum":"18","mr":"21:19","ms":"06:49","pcpn":"0.0","pop":"0","pres":"1020","sr":"05:15","ss":"19:10","tmp_max":"24","tmp_min":"13","uv_index":"6","vis":"20","wind_deg":"210","wind_dir":"西南风","wind_sc":"3-4","wind_spd":"21"},{"cond_code_d":"100","cond_code_n":"100","cond_txt_d":"晴","cond_txt_n":"晴","date":"2018-05-03","hum":"20","mr":"22:14","ms":"07:28","pcpn":"0.0","pop":"0","pres":"1022","sr":"05:13","ss":"19:11","tmp_max":"24","tmp_min":"13","uv_index":"7","vis":"20","wind_deg":"177","wind_dir":"南风","wind_sc":"1-2","wind_spd":"4"}]
* lifestyle : [{"type":"comf","brf":"舒适","txt":"白天不太热也不太冷,风力不大,相信您在这样的天气条件下,应会感到比较清爽和舒适。"},{"type":"drsg","brf":"较舒适","txt":"建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物,宜着夹克衫、薄毛衣等。"},{"type":"flu","brf":"较易发","txt":"虽然温度适宜但风力较大,仍较易发生感冒,体质较弱的朋友请注意适当防护。"},{"type":"sport","brf":"较适宜","txt":"阴天,较适宜进行各种户内外运动。"},{"type":"trav","brf":"适宜","txt":"天气较好,风稍大,但温度适宜,总体来说还是好天气。这样的天气适宜旅游,您可以尽情享受大自然的风光。"},{"type":"uv","brf":"最弱","txt":"属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。"},{"type":"cw","brf":"较不宜","txt":"较不宜洗车,未来一天无雨,风力较大,如果执意擦洗汽车,要做好蒙上污垢的心理准备。"},{"type":"air","brf":"良","txt":"气象条件有利于空气污染物稀释、扩散和清除,可在室外正常活动。"}]
*/
private BasicBean basic;
private UpdateBean update;
private String status;
private NowBean now;
private List daily_forecast;
private List lifestyle;
public BasicBean getBasic() {
return basic;
}
public void setBasic(BasicBean basic) {
this.basic = basic;
}
public UpdateBean getUpdate() {
return update;
}
public void setUpdate(UpdateBean update) {
this.update = update;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public NowBean getNow() {
return now;
}
public void setNow(NowBean now) {
this.now = now;
}
public List getDaily_forecast() {
return daily_forecast;
}
public void setDaily_forecast(List daily_forecast) {
this.daily_forecast = daily_forecast;
}
public List getLifestyle() {
return lifestyle;
}
public void setLifestyle(List lifestyle) {
this.lifestyle = lifestyle;
}
public static class BasicBean {
/**
* cid : CN101010100
* location : 北京
* parent_city : 北京
* admin_area : 北京
* cnty : 中国
* lat : 39.90498734
* lon : 116.4052887
* tz : +8.00
*/
private String cid;
private String location;
private String parent_city;
private String admin_area;
private String cnty;
private String lat;
private String lon;
private String tz;
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getParent_city() {
return parent_city;
}
public void setParent_city(String parent_city) {
this.parent_city = parent_city;
}
public String getAdmin_area() {
return admin_area;
}
public void setAdmin_area(String admin_area) {
this.admin_area = admin_area;
}
public String getCnty() {
return cnty;
}
public void setCnty(String cnty) {
this.cnty = cnty;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getTz() {
return tz;
}
public void setTz(String tz) {
this.tz = tz;
}
}
public static class UpdateBean {
/**
* loc : 2018-05-01 14:47
* utc : 2018-05-01 06:47
*/
private String loc;
private String utc;
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public String getUtc() {
return utc;
}
public void setUtc(String utc) {
this.utc = utc;
}
}
public static class NowBean {
/**
* cloud : 0
* cond_code : 504
* cond_txt : 浮尘
* fl : 18
* hum : 26
* pcpn : 0.0
* pres : 1013
* tmp : 21
* vis : 10
* wind_deg : 72
* wind_dir : 东北风
* wind_sc : 3
* wind_spd : 14
*/
private String cloud;
private String cond_code;
private String cond_txt;
private String fl;
private String hum;
private String pcpn;
private String pres;
private String tmp;
private String vis;
private String wind_deg;
private String wind_dir;
private String wind_sc;
private String wind_spd;
public String getCloud() {
return cloud;
}
public void setCloud(String cloud) {
this.cloud = cloud;
}
public String getCond_code() {
return cond_code;
}
public void setCond_code(String cond_code) {
this.cond_code = cond_code;
}
public String getCond_txt() {
return cond_txt;
}
public void setCond_txt(String cond_txt) {
this.cond_txt = cond_txt;
}
public String getFl() {
return fl;
}
public void setFl(String fl) {
this.fl = fl;
}
public String getHum() {
return hum;
}
public void setHum(String hum) {
this.hum = hum;
}
public String getPcpn() {
return pcpn;
}
public void setPcpn(String pcpn) {
this.pcpn = pcpn;
}
public String getPres() {
return pres;
}
public void setPres(String pres) {
this.pres = pres;
}
public String getTmp() {
return tmp;
}
public void setTmp(String tmp) {
this.tmp = tmp;
}
public String getVis() {
return vis;
}
public void setVis(String vis) {
this.vis = vis;
}
public String getWind_deg() {
return wind_deg;
}
public void setWind_deg(String wind_deg) {
this.wind_deg = wind_deg;
}
public String getWind_dir() {
return wind_dir;
}
public void setWind_dir(String wind_dir) {
this.wind_dir = wind_dir;
}
public String getWind_sc() {
return wind_sc;
}
public void setWind_sc(String wind_sc) {
this.wind_sc = wind_sc;
}
public String getWind_spd() {
return wind_spd;
}
public void setWind_spd(String wind_spd) {
this.wind_spd = wind_spd;
}
}
public static class DailyForecastBean {
/**
* cond_code_d : 504
* cond_code_n : 101
* cond_txt_d : 浮尘
* cond_txt_n : 多云
* date : 2018-05-01
* hum : 35
* mr : 20:19
* ms : 06:13
* pcpn : 0.0
* pop : 0
* pres : 1015
* sr : 05:16
* ss : 19:09
* tmp_max : 24
* tmp_min : 13
* uv_index : 6
* vis : 20
* wind_deg : 3
* wind_dir : 北风
* wind_sc : 4-5
* wind_spd : 33
*/
private String cond_code_d;
private String cond_code_n;
private String cond_txt_d;
private String cond_txt_n;
private String date;
private String hum;
private String mr;
private String ms;
private String pcpn;
private String pop;
private String pres;
private String sr;
private String ss;
private String tmp_max;
private String tmp_min;
private String uv_index;
private String vis;
private String wind_deg;
private String wind_dir;
private String wind_sc;
private String wind_spd;
public String getCond_code_d() {
return cond_code_d;
}
public void setCond_code_d(String cond_code_d) {
this.cond_code_d = cond_code_d;
}
public String getCond_code_n() {
return cond_code_n;
}
public void setCond_code_n(String cond_code_n) {
this.cond_code_n = cond_code_n;
}
public String getCond_txt_d() {
return cond_txt_d;
}
public void setCond_txt_d(String cond_txt_d) {
this.cond_txt_d = cond_txt_d;
}
public String getCond_txt_n() {
return cond_txt_n;
}
public void setCond_txt_n(String cond_txt_n) {
this.cond_txt_n = cond_txt_n;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getHum() {
return hum;
}
public void setHum(String hum) {
this.hum = hum;
}
public String getMr() {
return mr;
}
public void setMr(String mr) {
this.mr = mr;
}
public String getMs() {
return ms;
}
public void setMs(String ms) {
this.ms = ms;
}
public String getPcpn() {
return pcpn;
}
public void setPcpn(String pcpn) {
this.pcpn = pcpn;
}
public String getPop() {
return pop;
}
public void setPop(String pop) {
this.pop = pop;
}
public String getPres() {
return pres;
}
public void setPres(String pres) {
this.pres = pres;
}
public String getSr() {
return sr;
}
public void setSr(String sr) {
this.sr = sr;
}
public String getSs() {
return ss;
}
public void setSs(String ss) {
this.ss = ss;
}
public String getTmp_max() {
return tmp_max;
}
public void setTmp_max(String tmp_max) {
this.tmp_max = tmp_max;
}
public String getTmp_min() {
return tmp_min;
}
public void setTmp_min(String tmp_min) {
this.tmp_min = tmp_min;
}
public String getUv_index() {
return uv_index;
}
public void setUv_index(String uv_index) {
this.uv_index = uv_index;
}
public String getVis() {
return vis;
}
public void setVis(String vis) {
this.vis = vis;
}
public String getWind_deg() {
return wind_deg;
}
public void setWind_deg(String wind_deg) {
this.wind_deg = wind_deg;
}
public String getWind_dir() {
return wind_dir;
}
public void setWind_dir(String wind_dir) {
this.wind_dir = wind_dir;
}
public String getWind_sc() {
return wind_sc;
}
public void setWind_sc(String wind_sc) {
this.wind_sc = wind_sc;
}
public String getWind_spd() {
return wind_spd;
}
public void setWind_spd(String wind_spd) {
this.wind_spd = wind_spd;
}
}
public static class LifestyleBean {
/**
* type : comf
* brf : 舒适
* txt : 白天不太热也不太冷,风力不大,相信您在这样的天气条件下,应会感到比较清爽和舒适。
*/
private String type;
private String brf;
private String txt;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBrf() {
return brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
}
}
}
有了这个JavaBean就好办事了,直接在需要调用的地方调用解析就行(PS:博主很懒,懒得去优化代码了。明明是可以用butterknife来做得,不用敲那么多的手敲代码,非要做这样的蠢事。不过这个代码是博主很早之前就已经做好了的,就没有去修改优化了,这也是最近想写写博客突然想起这个demo就拉出来用用而已)
public class MainActivity extends AppCompatActivity {
RequestQueue queue = null;
EditText et_location;
TextView tv_city, tv_date, tv_max_temp, tv_min_temp, tv_temp, tv_cond, tv_dir, tv_comf, tv_suggest,
tv_pre_day1_maxtmp, tv_pre_day1_mintmp, tv_pre_day1_cond, tv_pre_day1_wind,
tv_pre_day2_maxtmp, tv_pre_day2_mintmp, tv_pre_day2_cond, tv_pre_day2_wind,
tv_pre_day3_maxtmp, tv_pre_day3_mintmp, tv_pre_day3_cond, tv_pre_day3_wind,
title_pre, title_pre_day1, title_pre_day2, title_pre_day3;
Editable location;
LinearLayoutCompat ly_container;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
setContentView(R.layout.activity_main);
ly_container= (LinearLayoutCompat) findViewById(R.id.ly_container);
queue = Volley.newRequestQueue(this);
et_location = (EditText) findViewById(R.id.et_location);
tv_city = (TextView) findViewById(R.id.id_tv_city);
tv_date = (TextView) findViewById(R.id.id_tv_date);
tv_max_temp = (TextView) findViewById(R.id.id_tv_max_temp);
tv_min_temp = (TextView) findViewById(R.id.id_tv_min_temp);
tv_temp = (TextView) findViewById(R.id.id_tv_temp);
tv_cond = (TextView) findViewById(R.id.id_tv_cond);
tv_dir = (TextView) findViewById(R.id.id_tv_dir);
tv_comf = (TextView) findViewById(R.id.id_tv_comf);
tv_suggest = (TextView) findViewById(R.id.id_tv_suggest);
title_pre = (TextView) findViewById(R.id.title_pre);
title_pre_day1 = (TextView) findViewById(R.id.title_pre_day1);
title_pre_day2 = (TextView) findViewById(R.id.title_pre_day2);
title_pre_day3 = (TextView) findViewById(R.id.title_pre_day3);
//未来三天天气
tv_pre_day1_maxtmp = (TextView) findViewById(R.id.tv_pre_day1_maxtmp);
tv_pre_day1_mintmp = (TextView) findViewById(R.id.tv_pre_day1_mintmp);
tv_pre_day1_cond = (TextView) findViewById(R.id.tv_pre_day1_cond);
tv_pre_day1_wind = (TextView) findViewById(R.id.tv_pre_day1_wind);
tv_pre_day2_maxtmp = (TextView) findViewById(R.id.tv_pre_day2_maxtmp);
tv_pre_day2_mintmp = (TextView) findViewById(R.id.tv_pre_day2_mintmp);
tv_pre_day2_cond = (TextView) findViewById(R.id.tv_pre_day2_cond);
tv_pre_day2_wind = (TextView) findViewById(R.id.tv_pre_day2_wind);
tv_pre_day3_maxtmp = (TextView) findViewById(R.id.tv_pre_day3_maxtmp);
tv_pre_day3_mintmp = (TextView) findViewById(R.id.tv_pre_day3_mintmp);
tv_pre_day3_cond = (TextView) findViewById(R.id.tv_pre_day3_cond);
tv_pre_day3_wind = (TextView) findViewById(R.id.tv_pre_day3_wind);
}
public void weatherClick(View view) {
location = et_location.getText();
String url = "https://free-api.heweather.com/s6/weather?location=" + location + "&key=0754508fbe0f44be915c65a0182b8aa9";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
@Override
public void onResponse(JSONObject jsonObject) {
ly_container.setBackgroundResource(R.mipmap.sky);
title_pre.setVisibility(View.VISIBLE);
title_pre_day1.setVisibility(View.VISIBLE);
title_pre_day2.setVisibility(View.VISIBLE);
title_pre_day3.setVisibility(View.VISIBLE);
System.out.println(jsonObject);
Gson gson = new Gson();
WeatherBean weatherBean = gson.fromJson(jsonObject.toString(), WeatherBean.class);
String cityName = weatherBean.getHeWeather6().get(0).getBasic().getLocation();
String date = weatherBean.getHeWeather6().get(0).getDaily_forecast().get(0).getDate();
String maxtemp = weatherBean.getHeWeather6().get(0).getDaily_forecast().get(0).getTmp_max();
String mintemp = weatherBean.getHeWeather6().get(0).getDaily_forecast().get(0).getTmp_min();
String temp = weatherBean.getHeWeather6().get(0).getNow().getTmp();
String cond = weatherBean.getHeWeather6().get(0).getNow().getCond_txt();
String dir = weatherBean.getHeWeather6().get(0).getNow().getWind_dir();
String comf = weatherBean.getHeWeather6().get(0).getLifestyle().get(0).getBrf();
String suggest = weatherBean.getHeWeather6().get(0).getLifestyle().get(0).getTxt();
String day1_maxtmp=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(0).getTmp_max();
String day1_mintmp=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(0).getTmp_min();
String day1_cond=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(0).getCond_txt_n();
String day1_wind=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(0).getWind_dir();
String day2_maxtmp=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(1).getTmp_max();
String day2_mintmp=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(1).getTmp_min();
String day2_cond=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(1).getCond_txt_n();
String day2_wind=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(1).getWind_dir();
String day3_maxtmp=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(2).getTmp_max();
String day3_mintmp=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(2).getTmp_min();
String day3_cond=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(2).getCond_txt_n();
String day3_wind=weatherBean.getHeWeather6().get(0).getDaily_forecast().get(2).getWind_dir();
tv_city.setText("城市:" + cityName);
tv_date.setText("日期:" + date);
tv_max_temp.setText("最高温度:" + maxtemp);
tv_min_temp.setText("最低温度:" + mintemp);
tv_temp.setText("实时温度:" + temp);
tv_cond.setText("天气情况:" + cond);
tv_dir.setText("风向:" + dir);
tv_comf.setText("人体感觉:" + comf);
tv_suggest.setText("建议:" + suggest);
tv_pre_day1_maxtmp.setText("最高温度:" + day1_maxtmp);
tv_pre_day1_mintmp.setText("最低温度:" + day1_mintmp);
tv_pre_day1_cond.setText("天气:" + day1_cond);
tv_pre_day1_wind.setText("风向:" + day1_wind);
tv_pre_day2_maxtmp.setText("最高温度:" + day2_maxtmp);
tv_pre_day2_mintmp.setText("最低温度:" + day2_mintmp);
tv_pre_day2_cond.setText("天气:" + day2_cond);
tv_pre_day2_wind.setText("风向:" + day2_wind);
tv_pre_day3_maxtmp.setText("最高温度:" + day3_maxtmp);
tv_pre_day3_mintmp.setText("最低温度:" + day3_mintmp);
tv_pre_day3_cond.setText("天气:" + day3_cond);
tv_pre_day3_wind.setText("风向:" + day3_wind);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
System.out.println(volleyError);
}
});
queue.add(request);
}
}
由于我写这个代码的时候用了很多TextView,免得大家乱套了,在这里就给出我当时的xml代码吧。
对了,记得给AndroidManifest一个可以访问网络的权限哦,不然我们怎么请求数据呢。
好,说了一大堆废话,直接上最终效果图吧。。。。。。
背景图什么的换为你自己喜欢的就好,哈哈,这不是重点。
点击“查询天气”按键就切换背景图以及获取到JSON数据并解析出来了,好,到此结束,博主溜了......