//网络获取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;
im
[个人学习笔记]Android 从网络获取json并解析 --Demo
最新推荐文章于 2023-05-31 09:57:48 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)