JAVA获得天气json数据的方法,使用Json_lib解析json数据获得当天天气情况

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.ProtocolException;

import java.net.URL;

import org.apache.commons.lang.StringEscapeUtils;

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

public class Json {

/**

* @param args

* @throws UnsupportedEncodingException

*/

public static void main(String[] args) throws UnsupportedEncodingException {

String path = "http://m.weather.com.cn/data/101010100.html";

URL url;

String inputline="";String info="";

try {

url = new URL(path);

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.setReadTimeout(10*1000);

conn.setRequestMethod("GET");

InputStreamReader inStream = new InputStreamReader(conn.getInputStream(),"UTF-8");

BufferedReader buffer=new BufferedReader(inStream);

while((inputline=buffer.readLine())!=null){

info+=inputline;

}

} catch (ProtocolException e) {

e.printStackTrace();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

JSONObject jsonob = JSONObject.fromObject((JSONObject.fromObject(info).getString("weatherinfo")));

String city = jsonob.getString("city");

System.out.println(city);

String date_y = jsonob.getString("date_y");

System.out.println(date_y);

String temp1 = jsonob.getString("temp1");

System.out.println(temp1);

String index_d = jsonob.getString("index_d");

System.out.println(index_d);

//解析的数据格式2:{"classroom":"0801","peoples":[{"field1":"name1","field2":"age1"},{"field0":"name2","field2":"age2说"}]}

info="{\"classroom\":\"0801\",\"peoples\":[{\"field1\":\"name1\",\"field2\":\"age1\"},{\"field1\":\"name2\",\"field2\":\"age2\"}]}";

jsonob = JSONObject.fromObject(info);

String classname = jsonob.getString("classroom");

System.out.println(classname);

JSONArray jsons = jsonob.getJSONArray("peoples");

int jsonLength = jsons.size();

//对json数组进行循环

for (int i = 0; i < jsonLength; i++) {

JSONObject tempJson = JSONObject.fromObject(jsons.get(i));

String name = StringEscapeUtils.escapeSql(tempJson.getString("field1"));

String age = StringEscapeUtils.escapeSql(tempJson.getString("field2"));

System.out.println(name+"-"+age);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值