[个人学习笔记]Android 从网络获取json并解析 --Demo

来源:互联网 发布:java swing文档 编辑:程序博客网 时间:2024/05/06 21:44

//网络获取json的方法
public String getJsonFromInternet(String url) throws MalformedURLException,IOException {
String resultString = "";
InputStreamReader isrInputStreamReader = new InputStreamReader(new URL(url).openStream());//从网上获取json的字节流
BufferedReader brBufferedReader = new BufferedReader(isrInputStreamReader);//将字节流转换成字符流
String line = "";
while ((line = brBufferedReader.readLine()) != null) 
{
resultString += line;
}
return resultString;//读取网上的json格式的字符串并返回
}
//需要特别注意的是获取json的方法需要脱离UI线程使用,
//可以使用AsyncTask中doInBackground获取网络jsonString




//用json字符串读取内部相关数据
{
    "weatherinfo": {//需要调用getJSONObject("weatherinfo")来获取下面的数据
        "city": "杭州",
        "city_en": "hangzhou",
        "date_y": "2015年6月18日",
        "date": "",
        "week": "星期四",
        "fchh": "11",
        "cityid": "101210101",
        "temp1": "24℃~20℃",
        "weather1": "阵雨转阴"
    }
}//这个是从网上获取到的json字符串






//从json字符串中获取相关的数据的方法
public weather(String json) throws JSONException {
// TODO Auto-generated constructor stub
JSONObject ja=new JSONObject(json).getJSONObject("weatherinfo");
//获取字符串中weatherinfo中的数据并复制给当前的jsonobject对象
//这个是获取到jsonstring中只有一个对象数据的情况下获取数据使用的
setCity(ja.getString("city"));//从ja对象中获取需要的相关信息
setTime(ja.getString("date_y"));
setWeek(ja.getString("week"));
setWeather(ja.getString("weather1"));
setTemp(ja.getString("temp1"));
}






// 从网上获取json并解析数据后显示在view上的demo
//MainActivity.class
package com.example.testjson;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;


public class MainActivity extends Activity {
private weather mw;
private TextView date;
private TextView city;
private TextView weather;
private TextView temp;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
date = (TextView) findViewById(R.id.date);
temp = (TextView) findViewById(R.id.temp);
city = (TextView) findViewById(R.id.city);
weather = (TextView) findViewById(R.id.weather);
new backgetjson(date, city, weather, temp)
.execute("http://m.weather.com.cn/atad/101210101.html");
}


public String getJsonFromInternet(String url) throws MalformedURLException,
IOException {
String resultString = "";
InputStreamReader isrInputStreamReader = new InputStreamReader(new URL(
url).openStream());
BufferedReader brBufferedReader = new BufferedReader(
isrInputStreamReader);
String line = "";
while ((line = brBufferedReader.readLine()) != null) {
resultString += line;
}
return resultString;
}


class backgetjson extends AsyncTask<String, Void, String> {
private weather mw;
private TextView date;
private TextView city;
private TextView weather;
private TextView temp;


public backgetjson(TextView d, TextView c, TextView w, TextView t) {
// TODO Auto-generated constructor stub
date = d;
city = c;
weather = w;
temp = t;
}


@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String jsString = "";
try {
jsString = getJsonFromInternet(params[0]);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsString;
}


@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
mw = new weather(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
date.setText(mw.getTime());
city.setText(mw.getCity());
weather.setText(mw.getWeather());
temp.setText(mw.getTemp());
}


}


}






//weather.class
package com.example.testjson;


import org.json.JSONException;
import org.json.JSONObject;


public class weather {
private String city;
private String time;
private String week;
private String weather;
private String temp;


public String getCity() {
return city;
}


public void setCity(String city) {
this.city = city;
}


public String getTime() {
return time;
}


public void setTime(String time) {
this.time = time;
}


public String getWeek() {
return week;
}


public void setWeek(String week) {
this.week = week;
}


public String getWeather() {
return weather;
}


public void setWeather(String weather) {
this.weather = weather;
}


public String getTemp() {
return temp;
}


public void setTemp(String temp) {
this.temp = temp;
}


public weather() {
// TODO Auto-generated constructor stub
}


public weather(String json) throws JSONException {
// TODO Auto-generated constructor stub
JSONObject ja = new JSONObject(json).getJSONObject("weatherinfo");
setCity(ja.getString("city"));
setTime(ja.getString("date_y"));
setWeek(ja.getString("week"));
setWeather(ja.getString("weather1"));
setTemp(ja.getString("temp1"));
}
}








// 如果获取的json字符串中有如下结构的可以解析成jsonarray
{
    status: 1,
    data: -[
        -{
            id: 1,
            name: "Tony老师聊shell——环境变量配置文件",
            picSmall: "http://img.mukewang.com/55237dcc0001128c06000338-300-170.jpg",
            picBig: "http://img.mukewang.com/55237dcc0001128c06000338.jpg",
            description: "为你带来shell中的环境变量配置文件",
            learner: 12312
        },
        -{
            id: 2,
            name: "数学知识在CSS动画中的应用",
            picSmall: "http://img.mukewang.com/55249cf30001ae8a06000338-300-170.jpg",
            picBig: "http://img.mukewang.com/55249cf30001ae8a06000338.jpg",
            description: "数学知识与CSS结合实现酷炫效果",
            learner: 45625
        },
        -{
            id: 3,
            name: "Oracle数据库开发必备利器之PL/SQL基础",
            picSmall: "http://img.mukewang.com/5523711700016d1606000338-300-170.jpg",
            picBig: "http://img.mukewang.com/5523711700016d1606000338.jpg",
            description: "Oracle数据库高级开发必备的基础。",
            learner: 41236
        },
        -{
            id: 4,
            name: "Android见证消息推送时刻进阶篇",
            picSmall: "http://img.mukewang.com/551e470500018dd806000338-300-170.jpg",
            picBig: "http://img.mukewang.com/551e470500018dd806000338.jpg",
            description: "Android消息推送就在眼前,Come on",
            learner: 45456
        },
}
//解析代码如下
JSONObject ja=new JSONObject(json);
JSONArray jsonarray=ja.getJSONArray("data");
for (int i=0;i<jsonarray.length();i++)
{
ja=jsonarray.getJSONObject(i);
.....//这里得到了一个jsonobject
//得到一个jsonobject之后可以直接从里面获取数据。
//方法与前面获取数据的方法一样可以从中获取类似于一个arraylist的对象
}


Demo 下载链接:http://download.csdn.net/detail/apple_can/8839713



0 0
原创粉丝点击