android studio处理网络jason文件

来源:互联网 发布:juniper client mac 编辑:程序博客网 时间:2024/06/05 23:54

首先打开网址:aqicn.org

打开:http://aqicn.org/publishingdata/json

public class MainActivity extends AppCompatActivity {    private TextView tv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tv = (TextView) findViewById(R.id.text);        new AsyncTask<Void, Void, String>() {            @Override            protected String doInBackground(Void... voids) {                try {                    InputStream inputStream = new URL("http://aqicn.org/publishingdata/json").openStream();                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));                    String line = null;                    StringBuffer stringBuffer = new StringBuffer();                    while ((line = reader.readLine()) != null) {                        stringBuffer.append(line);                    }                    reader.close();                    return stringBuffer.toString();                } catch (IOException e) {                    e.printStackTrace();                }                return null;            }            @Override            protected void onPostExecute (String s){                super.onPostExecute(s);                if (s != null) {                    try {                        JSONArray jsonArray = new JSONArray(s);                        JSONObject jsonObject = jsonArray.getJSONObject(0);                        JSONArray jsonArray1 = jsonObject.getJSONArray("pollutants");                        JSONObject jsonObject1 = jsonArray1.getJSONObject(0);                        tv.setText(String.format("%s %s: %f", jsonObject.getString("cityName"), jsonObject.getString("localName"), jsonObject1.getDouble("value")));                    } catch (JSONException e) {                        e.printStackTrace();                    }                }            }        }.execute();    }}

0 0
原创粉丝点击