JSON是网络传输中数据组织的一种格式。
下面为几个不同的JSON数据:
1."{name:‘jack‘,age:23}"
2."{student:{name:‘jack‘,age:23}}"
3."{students:[{name:‘jack‘,age:23},{name:‘lily‘,age:22}]}"
4."{object:{persons:[{name:‘呵呵‘,image:‘http://192.168.56.1:8080/Web/ok.jpg‘},{name:‘哈哈‘,image:‘http://192.168.56.1:8080/Web/s1.png‘},{name:‘嘿嘿‘,image:‘http://192.168.56.1:8080/Web/s2.jpg‘}]}}"
5."[{school:‘pku‘,good:‘false‘,class:{name:‘android‘,count:40}},{school:‘pku‘,good:‘true‘,class:{name:‘ios‘,count:45}}]"
6."{status:2,result:[{company_name:‘pku1‘,company_id:1}, {company_name:‘pku2‘,company_id:5},{company_name:‘pku3‘,company_id:7}]}"
对于JSON数据的第一印象:JSON数据就是字符串,且包含在大括号之间,且字符串中的数据是有一定结构的,而且每一部分数据好像采用的是键值映射的关系。
JSON的简单介绍:
1.
2.
3.
大概总结下,就是JSON字符串,是包含在大括号里,组织数据有两种方式,一是键值对,二是数组,通过这两种,采用符合规范的结构,你可以自己写出任意自定义任意长的JSON数据,检查一个JSON数据是否正确,可以通过一个网址http://www.bejson.com/,输入你自己写的json字符串,它可以帮你校验。
那么如何解析JSON字符串呢?
进行解析,首先要导入一个JSON解析相关的jar包(在Android开发下这个包已经自动导入了,而Java中需要下载并导入包),这个包下有两个重要的类,分别是JSONObject和JSONArray,分别与上面讲的键值对和数组一一对应。
下面是解析几个简单JSON字符串的例子,可以很好帮助入门JSON解析:
1.
1 String json = "{name:‘Jack‘,age:20,address:‘beijing‘}"; 2 3 JSONObject object = new JSONObject(json); 4 5 String name = object.getString("name"); 6 int age = object.getInt("age"); 7 String address = object.getString("address"); 8 System.out.println(name+","+age+","+address);
2.
1 String json = "{student:{address:‘beijing‘,age:18,name:‘Lucy‘}}"; 2 3 JSONObject obj = new JSONObject(json); 4 JSONObject object = obj.getJSONObject("student"); 5 6 String address = object.getString("address"); 7 int age = object.getInt("age"); 8 String name = object.getString("name"); 9 System.out.println(address+","+age+","+name);
3.
1 String json = "{students:[{address:‘shanghai‘,age:23,name:‘xiaobai‘},{address:‘shenzhen‘,age:24,name:‘xiaohei‘}]}"; 2 3 JSONObject object = new JSONObject(json); 4 JSONArray array = object.getJSONArray("students"); 5 6 //遍历数组,得到每个对象 7 for(int i=0;i<array.length();i++) 8 { 9 JSONObject obj = array.getJSONObject(i); 10 String address = obj.getString("address"); 11 int age = obj.getInt("age"); 12 String name = obj.getString("name"); 13 System.out.println(address+","+age+","+name); 14 }
4.
1 String json = "{object:{persons:[{name:‘呵呵‘,image:‘http://192.168.56.1:8080/Web/ok.jpg‘},{name:‘哈哈‘,image:‘http://192.168.56.1:8080/Web/s1.png‘},{name:‘嘿嘿‘,image:‘http://192.168.56.1:8080/Web/s2.jpg‘}]}}"; 2 3 JSONObject object = new JSONObject(json); 4 5 JSONObject obj = object.getJSONObject("object"); 6 7 JSONArray array = obj.getJSONArray("persons"); 8 9 for(int i=0;i<array.length();i++) 10 { 11 JSONObject jsonObj = array.getJSONObject(i); 12 13 String name = jsonObj.getString("name"); 14 String image = jsonObj.getString("image"); 15 System.out.println(name+","+image); 16 17 }
5.
1 String json="[{school:‘bpk1‘,good:‘false‘,class:{name:‘android‘,count:40}},{school:‘pku2‘,good:‘true‘,class:{name:‘ios‘,count:45}}]"; 2 3 JSONArray array = new JSONArray(json); 4 5 for(int i=0;i<array.length();i++) 6 { 7 JSONObject obj = array.getJSONObject(i); 8 String school = obj.getString("school"); 9 String good = obj.getString("good"); 10 JSONObject object = obj.getJSONObject("class"); 11 String name = object.getString("name"); 12 int count = object.getInt("count"); 13 14 System.out.println(school+","+good+","+name+","+count); 15 }
6.
1 String json="{status:2,result:[{company_name:‘pku1‘,company_id:1}, {company_name:‘pku2‘,company_id:5},{company_name:‘pku3‘,company_id:7}]}"; 2 3 4 JSONObject object = new JSONObject(json); 5 String status = object.getString("status"); 6 System.out.println(status); 7 8 JSONArray array = object.getJSONArray("result"); 9 for(int i=0;i<array.length();i++) 10 { 11 JSONObject obj = array.getJSONObject(i); 12 String comName = obj.getString("company_name"); 13 int comId = obj.getInt("company_id"); 14 15 System.out.println(comName+","+comId); 16 }
总结以上:关于JSON数据的解析,无非就是JSONObject和JSONArray根据实际的JSON字符串的结构灵活使用,当获取的是对象,使用的是JSONObject,当获取的是一个数组,使用的是JSONArray,让后取出数据总是从JSONObject中根据键取出相对应的数据。
示例:看一个比较复杂的例子,从网络上获取JSON字符串,然后解析出来
1 { 2 "cityname": "双鸭山", 3 "citycode": "101051301", 4 "citydesc": "黑龙江 双鸭山", 5 "publishtime": "2015年09月17日10:00", 6 "lastupdate": "2015-09-17 10:50:04", 7 "data": [ 8 { 9 "date": "2015-09-17", 10 "icon": "d00|n00", 11 "weather": "晴", 12 "temperature": "29°C/15°C", 13 "winddirect": "南风微风" 14 }, 15 { 16 "date": "2015-09-18", 17 "icon": "d00|n00", 18 "weather": "晴", 19 "temperature": "27°C/14°C", 20 "winddirect": "南风微风" 21 }, 22 { 23 "date": "2015-09-19", 24 "icon": "d03|n01", 25 "weather": "阵雨转多云", 26 "temperature": "24°C/13°C", 27 "winddirect": "东南风微风" 28 }, 29 { 30 "date": "2015-09-20", 31 "icon": "d00|n00", 32 "weather": "晴", 33 "temperature": "22°C/12°C", 34 "winddirect": "东南风转西风微风" 35 }, 36 { 37 "date": "2015-09-21", 38 "icon": "d00|n00", 39 "weather": "晴", 40 "temperature": "23°C/14°C", 41 "winddirect": "西风3-4级" 42 }, 43 { 44 "date": "2015-09-22", 45 "icon": "d00|n01", 46 "weather": "晴转多云", 47 "temperature": "25°C/13°C", 48 "winddirect": "西南风3-4级" 49 } 50 ], 51 "live": { 52 "updatetime": null, 53 "temperature": "℃", 54 "humidity": null, 55 "winddirect": "" 56 } 57 }
JSON字符串
1 package com.qianfeng.json3; 2 3 import java.util.List; 4 5 public class Weather { 6 7 private String cityName; 8 private String cityCode; 9 private String cityDesc; 10 private String publishtime; 11 private String lastupdate; 12 private List<WeatherData> datas; 13 private Live live; 14 15 public Weather(){} 16 17 public Weather(String cityName, String cityCode, String cityDesc, 18 String publishtime, String lastupdate, List<WeatherData> datas, 19 Live live) { 20 super(); 21 this.cityName = cityName; 22 this.cityCode = cityCode; 23 this.cityDesc = cityDesc; 24 this.publishtime = publishtime; 25 this.lastupdate = lastupdate; 26 this.datas = datas; 27 this.live = live; 28 } 29 30 public String getCityName() { 31 return cityName; 32 } 33 34 public void setCityName(String cityName) { 35 this.cityName = cityName; 36 } 37 38 public String getCityCode() { 39 return cityCode; 40 } 41 42 public void setCityCode(String cityCode) { 43 this.cityCode = cityCode; 44 } 45 46 public String getCityDesc() { 47 return cityDesc; 48 } 49 50 public void setCityDesc(String cityDesc) { 51 this.cityDesc = cityDesc; 52 } 53 54 public String getPublishtime() { 55 return publishtime; 56 } 57 58 public void setPublishtime(String publishtime) { 59 this.publishtime = publishtime; 60 } 61 62 public String getLastupdate() { 63 return lastupdate; 64 } 65 66 public void setLastupdate(String lastupdate) { 67 this.lastupdate = lastupdate; 68 } 69 70 public List<WeatherData> getDatas() { 71 return datas; 72 } 73 74 public void setDatas(List<WeatherData> datas) { 75 this.datas = datas; 76 } 77 78 public Live getLive() { 79 return live; 80 } 81 82 public void setLive(Live live) { 83 this.live = live; 84 } 85 86 @Override 87 public String toString() { 88 return "Weather [cityName=" + cityName + ", cityCode=" + cityCode 89 + ", cityDesc=" + cityDesc + ", publishtime=" + publishtime 90 + ", lastupdate=" + lastupdate + ", datas=" + datas + ", live=" 91 + live + "]"; 92 } 93 94 95 96 97 98 99 100 }
Weather.java
1 package com.qianfeng.json3; 2 3 public class WeatherData { 4 5 private String date; 6 private String icon; 7 private String weather; 8 private String temperature; 9 private String winddirect; 10 11 public WeatherData(){} 12 13 public WeatherData(String date, String icon, String weather, 14 String temperature, String winddirect) { 15 super(); 16 this.date = date; 17 this.icon = icon; 18 this.weather = weather; 19 this.temperature = temperature; 20 this.winddirect = winddirect; 21 } 22 23 public String getDate() { 24 return date; 25 } 26 27 public void setDate(String date) { 28 this.date = date; 29 } 30 31 public String getIcon() { 32 return icon; 33 } 34 35 public void setIcon(String icon) { 36 this.icon = icon; 37 } 38 39 public String getWeather() { 40 return weather; 41 } 42 43 public void setWeather(String weather) { 44 this.weather = weather; 45 } 46 47 public String getTemperature() { 48 return temperature; 49 } 50 51 public void setTemperature(String temperature) { 52 this.temperature = temperature; 53 } 54 55 public String getWinddirect() { 56 return winddirect; 57 } 58 59 public void setWinddirect(String winddirect) { 60 this.winddirect = winddirect; 61 } 62 63 @Override 64 public String toString() { 65 return "WeatherData [date=" + date + ", icon=" + icon + ", weather=" 66 + weather + ", temperature=" + temperature + ", winddirect=" 67 + winddirect + "]"; 68 } 69 }
WeatherData.java
1 package com.qianfeng.json3; 2 3 public class Live { 4 5 private String updatetime; 6 private String temperature; 7 private String humidity; 8 private String winddirect; 9 10 public Live(){} 11 12 public Live(String updatetime, String temperature, String humidity, 13 String winddirect) { 14 super(); 15 this.updatetime = updatetime; 16 this.temperature = temperature; 17 this.humidity = humidity; 18 this.winddirect = winddirect; 19 } 20 21 public String getUpdatetime() { 22 return updatetime; 23 } 24 25 public void setUpdatetime(String updatetime) { 26 this.updatetime = updatetime; 27 } 28 29 public String getTemperature() { 30 return temperature; 31 } 32 33 public void setTemperature(String temperature) { 34 this.temperature = temperature; 35 } 36 37 public String getHumidity() { 38 return humidity; 39 } 40 41 public void setHumidity(String humidity) { 42 this.humidity = humidity; 43 } 44 45 public String getWinddirect() { 46 return winddirect; 47 } 48 49 public void setWinddirect(String winddirect) { 50 this.winddirect = winddirect; 51 } 52 53 @Override 54 public String toString() { 55 return "Live [updatetime=" + updatetime + ", temperature=" 56 + temperature + ", humidity=" + humidity + ", winddirect=" 57 + winddirect + "]"; 58 } 59 60 61 62 }
Live.java
1 package com.qianfeng.json3; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.json.JSONArray; 7 import org.json.JSONException; 8 import org.json.JSONObject; 9 10 public class ParseTool { 11 12 public static Weather parserWeather(String jsonString) throws JSONException 13 { 14 Weather weather = new Weather(); 15 16 JSONObject object = new JSONObject(jsonString); 17 String cityname = object.getString("cityname"); 18 String citycode = object.getString("citycode"); 19 String citydesc = object.getString("citydesc"); 20 String publishtime = object.getString("publishtime"); 21 String lastupdate = object.getString("lastupdate"); 22 23 weather.setCityName(cityname); 24 weather.setCityCode(citycode); 25 weather.setCityDesc(citydesc); 26 weather.setPublishtime(publishtime); 27 weather.setLastupdate(lastupdate); 28 29 JSONArray array = object.getJSONArray("data"); 30 WeatherData data = null; 31 List<WeatherData> datas = new ArrayList<WeatherData>(); 32 for(int i=0;i<array.length();i++) 33 { 34 JSONObject obj = array.getJSONObject(i); 35 String date = obj.getString("date"); 36 String icon = obj.getString("icon"); 37 String weathers = obj.getString("weather"); 38 String temperature = obj.getString("temperature"); 39 String winddirect = obj.getString("winddirect"); 40 data = new WeatherData(); 41 data.setDate(date); 42 data.setIcon(icon); 43 data.setWeather(weathers); 44 data.setTemperature(temperature); 45 data.setWinddirect(winddirect); 46 datas.add(data); 47 } 48 49 weather.setDatas(datas); 50 51 JSONObject jsonObj = object.getJSONObject("live"); 52 String updatetime = jsonObj.getString("updatetime"); 53 String temperatures = jsonObj.getString("temperature"); 54 String humidity = jsonObj.getString("humidity"); 55 String winddirects = jsonObj.getString("winddirect"); 56 Live live = new Live(); 57 live.setUpdatetime(updatetime); 58 live.setTemperature(temperatures); 59 live.setHumidity(humidity); 60 live.setWinddirect(winddirects); 61 62 weather.setLive(live); 63 64 return weather; 65 } 66 67 }
ParseTool .java
1 package com.qianfeng.json3; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.net.HttpURLConnection; 7 import java.net.MalformedURLException; 8 import java.net.URL; 9 import java.util.ArrayList; 10 import java.util.List; 11 12 import org.json.JSONArray; 13 import org.json.JSONException; 14 import org.json.JSONObject; 15 16 public class HttpUtil { 17 18 // 获取服务器端json字符串 19 public static String getJsonStr(String path) throws IOException 20 { 21 URL url = new URL(path); 22 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 23 24 conn.setRequestMethod("GET"); 25 conn.setConnectTimeout(5000); 26 conn.setDoInput(true); 27 28 conn.connect(); 29 30 InputStream in = null; 31 if(conn.getResponseCode()==200) 32 { 33 in = conn.getInputStream(); 34 } 35 return changeToStr(in); 36 } 37 38 private static String changeToStr(InputStream in) throws IOException { 39 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 40 byte[] arr = new byte[1024]; 41 int len = 0; 42 while((len = in.read(arr))!=-1) 43 { 44 bos.write(arr,0,len); 45 } 46 return new String(bos.toByteArray(),"utf-8"); 47 } 48 49 50 51 }
HttpUtil.java
1 package com.qianfeng.json3; 2 3 import java.io.IOException; 4 5 import org.json.JSONException; 6 7 public class Test { 8 9 /** 10 * @param args 11 * @throws IOException 12 * @throws JSONException 13 */ 14 public static void main(String[] args) throws IOException, JSONException { 15 16 String path = "http://weather.xcyh.org/101051301/json/6"; 17 18 String jsonString = HttpUtil.getJsonStr(path); 19 20 Weather weather = ParseTool.parserWeather(jsonString); 21 22 System.out.println(weather); 23 24 } 25 }
Test.java
未完,待续。