您的位置:首页 > 移动开发 > Android开发

Android阶段学习笔记 7.25-7.29 之 解析聚合数据 全国天气预报 Json

2016-07-25 08:10 761 查看
一、聚合数据网站上拿到全过天气的json

1.在File->setting->plugins,搜索GsonFormat,下载。


2.聚合数据网址https://www.juhe.cn/以及聚合使用教程http://blog.csdn.net/u014449046/article/details/46869821根据聚合数据教程下载聚合数据sdk,在工程中导入jar包,

3.根据网站的链接下载某地天气预报的Json串,建javaBean类,Ctrl+Insert,选择,GsonFormat,插入从网页上下载的Json串,生成类的方法。

二、网页中拿到json的方法,一种是调用聚合封装的方法,需要进行一中的步骤二,进行导包,另一种是开启子线程,直接根据网址得到json。

这里给出开启子线程得到json的方法。

public class MainActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener {

Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
parser.setJson((String)msg.obj);
Context context = MainActivity.this;
Intent intent = new Intent(MainActivity.this, Main.class);
intent.putExtra("parser", parser);
startActivity(intent);

}
};

JsonParser parser = new JsonParser();
private String cityname = null;
private Button btn_get;
private Context myContext;
private AutoCompleteTextView et_city;
private String[] s ={"阿坝","阿拉善","阿里","安康"}  //省略数组中的地区名
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);

et_city = (AutoCompleteTextView) findViewById(R.id.et_city);
btn_get = (Button) findViewById(R.id.btn_get);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,s);
et_city.setAdapter(adapter);

et_city.setOnItemClickListener(this);
btn_get.setOnClickListener(this);

}

private class FutureInfoGetter {
private String path;
public FutureInfoGetter(String path) {
this.path = path;
}

private void  getFutureInfo() {
Thread t = new Thread() {
@Override
public void run() {
URL url = null;
try {

url = new URL(path);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);

con.connect();
//先建立连接,再生成响应码
//拿到服务器返回的输入流,流里的文件就是返回的html源文件
InputStream is = con.getInputStream();
//从流里面读取数据构成文本,封装成工具类
String text = Utils.getTextFromStream(is);
//发送消息,主线程刷新ui
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}

@Override
public void onClick(View v) {

try {

String city = URLEncoder.encode(cityname, "utf-8");
String path = "http://v.juhe.cn/weather/index?format=2&cityname=" + city + "&key=057de5d086c89d720e0614cc5c672829";

FutureInfoGetter futureInfoGetter = new FutureInfoGetter(path);
futureInfoGetter.getFutureInfo();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
cityname = parent.getItemAtPosition(position).toString();
}
}


三、解析Json串

Json串如图

"error_code": 0,
"reason": "successed!",
"result": {
"future": [
{
"date": "20160729",
"temperature": "30℃~39℃",
"weather": "晴",
"weather_id": {
"fa": "00",
"fb": "00"
},
"week": "星期五",
"wind": "东南风微风"
},
{
"date": "20160730",
"temperature": "29℃~38℃",
"weather": "晴",
"weather_id": {
"fa": "00",
"fb": "00"
},
"week": "星期六",
"wind": "东南风微风"
},
{
"date": "20160731",
"temperature": "28℃~36℃",
"weather": "多云转晴",
"weather_id": {
"fa": "01",
"fb": "00"
},
"week": "星期日",
"wind": "东南风微风"
},
{
"date": "20160801",
"temperature": "28℃~35℃",
"weather": "阴",
"weather_id": {
"fa": "02",
"fb": "02"
},
"week": "星期一",
"wind": "东南风微风"
},
{
"date": "20160802",
"temperature": "27℃~35℃",
"weather": "阴转阵雨",
"weather_id": {
"fa": "02",
"fb": "03"
},
"week": "星期二",
"wind": "东南风微风"
},
{
"date": "20160803",
"temperature": "29℃~38℃",
"weather": "晴",
"weather_id": {
"fa": "00",
"fb": "00"
},
"week": "星期三",
"wind": "东南风微风"
},
{
"date": "20160804",
"temperature": "29℃~38℃",
"weather": "晴",
"weather_id": {
"fa": "00",
"fb": "00"
},
"week": "星期四",
"wind": "东南风微风"
}
],
"sk": {
"humidity": "67%",
"temp": "31",
"time": "14:38",
"wind_direction": "东南风",
"wind_strength": "5级"
},
"today": {
"city": "苏州",
"comfort_index": "",
"date_y": "2016年07月29日",
"dressing_advice": "天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。",
"dressing_index": "炎热",
"drying_index": "",
"exercise_index": "较适宜",
"temperature": "30℃~39℃",
"travel_index": "较适宜",
"uv_index": "很强",
"wash_index": "较适宜",
"weather": "晴",
"weather_id": {
"fa": "00",
"fb": "00"
},
"week": "星期五",
"wind": "东南风微风"
}
},
"resultcode": "200"
}

分析整个json应该为一个JSONObject,error_code,reason,result,resultcode各为一个JsonObject,result中,又有today,sk两个JSONObject,future为一个JSONArray,解析方法如下:
为了方便调用,我把解析json方法全都定义在一个JsonParser类中,因为解析需要json串,便定义了json变量以及它的get,set方法。

只给出解析future时方法,其它方法类比,由于聚合sdk中封装的方法自动将JSONArray future解析成了JSONObject,每一天也都是object,且按照日期命名,因此解析时较困难,但juhe应该封装了方法,暂时没有发现,因此,不建议用聚合sdk封装的方法得到json。

public List<Bean.ResultBean.FutureBean> getFutureList(String json) {

List<Bean.ResultBean.FutureBean> futureList = new ArrayList<>();

if (json == null) {
Log.i("e", "json为空");
}

try {

JSONArray futureArray = null;

JSONObject  object = new JSONObject(json);
int errrorCode =  object.getInt("error_code");
String reason =  object.getString("reason");
int resultCode = object.getInt("resultcode");

if(resultCode == 200) {

JSONObject result = object.getJSONObject("result");
Log.i("result",result.toString());
futureArray = (JSONArray) result.get("future");

for (int i = 0; i < futureArray.length(); i++) {
Bean.ResultBean.FutureBean futureBean = new Bean.ResultBean.FutureBean();
JSONObject future = new JSONObject(futureArray.get(i).toString());
String date = future.getString("date").substring(4, 8);
String temp = future.getString("temperature");
String weather = future.getString("weather");
String week = future.getString("week");
String wind = future.getString("wind");

JSONObject weather_id =  future.getJSONObject("weather_id");
Bean.ResultBean.FutureBean.WeatherIdBean weatherIdBean = new Bean.ResultBean.FutureBean.WeatherIdBean();

String fa = weather_id.getString("fa");
String fb = weather_id.getString("fb");

weatherIdBean.setFa(fa);
weatherIdBean.setFb(fb);

futureBean.setWeather_id(weatherIdBean);
futureBean.setDate(date);
futureBean.setTemperature(temp);
futureBean.setWeather(weather);
futureBean.setWeek(week);
futureBean.setWind(wind);

futureList.add(futureBean);

}
} else {
Log.i("eee","返回码不对");
}

} catch (JSONException e) {
e.printStackTrace();
Log.d("666", "说明parseJson传进来的不是一个Json格式的数据,无法解析成为一个JsonObject");
}
return futureList;
// return null;
}

Json解析并不难,只要正确区分开JSONObject和JSONArray就没有问题了


好了,写完了,开心。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: