JSON

lib解析json数据获得当天天气情况

字号+ 作者:H5之家 来源:H5之家 2015-10-03 08:21 我要评论( )

Java使用Json_lib解析json数据获得当天天气情况 详见: http://blog.sina.com.cn/s/blog_62186b460100zqcb.html import java.io.BufferedReader;import java.io.

Java使用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 = ""; 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); } } }

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • Ajax+JSON基础实战视频教程

    Ajax+JSON基础实战视频教程

    2015-09-20 18:45

  • JSON 中文版

    JSON 中文版

    2015-09-13 11:07

网友点评