您的位置:首页 > Web前端 > JavaScript

我的Json解析实战

2015-10-16 16:59 603 查看
所谓json,其实就是在我们访问一个网页的接口的时候,服务器端传送给我们客户端的一种数据的结构,当然我们向服务器端发送的数据有时也会转换成json格式,当然了,这不是必须的。最近在解析一些json字符串,所以就贴出一些代码,也方便以后自己复习和使用。

首先先来一些简单的吧。

对一个json对象进行解析:

字符串原串是这样的:String json={“Persons”:[{“address”:”河南”,”name”:”郭XX”,”id”:201492115},{“address”:”大连”,”name”:”unName”,”id”:201492111}]},(我这里声明为String是不正确的格式,知识为了看起来方便)很明显可以看出在Persons这个key是对应一个数组的,而数组的内容则是一个对象,对象有三个成员变量address,name,id,每一个也都对应相应的value,下面让我们开始正式的解析吧,

代码如下:

public class TestJson {

public TestJson() {
// TODO Auto-generated constructor stub
}

public static void main(String []args){
JsonService jsonService=new JsonService();
//      Person person=(Person) jsonService.getPerson();
try {
String message=JsonTools.createJsonObject("Persons", jsonService.getListString());
System.out.println(message);
JSONObject jsonObject=new JSONObject(message);
JSONArray jsonArray=jsonObject.getJSONArray("Persons");
for(int i=0;i<jsonArray.length();i++){
Person p=new Person();
int id;
String name="";
String address="";
address=jsonArray.getJSONObject(i).getString("address");
name=jsonArray.getJSONObject(i).getString("name");
id=Integer.parseInt(jsonArray.getJSONObject(i).getString("id"));
p.setAddress(address);
p.setId(id);
p.setName(name);
System.out.println("Person:"+p.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


下面是解析的结果:

Person:Person [id=201492115, name=郭XX, address=河南]
Person:Person [id=201492111, name=unName, address=大连]


其中大致的原理是这样的,我们先声明一个JSONObject对象,然后将要进行解析的json字符串传进去,由于要解析的内容并非一个简单的键值对,而是一个对象,所以要使用JSONArray来获得一个数组,当然了,数组的获得还是需要依靠JsonObject对象的,然后对数组内每一个字符串对应的内容进行分别得解析就好了。

下面我会写一个比较复杂的json的解析过程(稍微有些bug,请不要介意啊,只是展示这么个思想,如果,博友们有好的方式,希望多多留言啊),接口传回的是一个json字符串,具体如下,{“error”:0,”status”:”success”,”date”:”2015-10-16”,”results”:[{“currentCity”:”成都”,”pm25”:”173”,”index”:[{“title”:”穿衣”,”zs”:”舒适”,”tipt”:”穿衣指数”,”des”:”建议着长袖T恤、衬衫加单裤等服装。年老体弱者宜着针织长袖衬衫、马甲和长裤。”},{“title”:”洗车”,”zs”:”不宜”,”tipt”:”洗车指数”,”des”:”不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。”},{“title”:”旅游”,”zs”:”适宜”,”tipt”:”旅游指数”,”des”:”天气较好,但丝毫不会影响您出行的心情。温度适宜又有微风相伴,适宜旅游。”},{“title”:”感冒”,”zs”:”较易发”,”tipt”:”感冒指数”,”des”:”昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。”},{“title”:”运动”,”zs”:”适宜”,”tipt”:”运动指数”,”des”:”天气较好,赶快投身大自然参与户外运动,尽情感受运动的快乐吧。”},{“title”:”紫外线强度”,”zs”:”弱”,”tipt”:”紫外线强度指数”,”des”:”紫外线强度较弱,建议出门前涂擦SPF在12-15之间、PA+的防晒护肤品。”}],”weather_data”:[{“date”:”周五 10月16日 (实时:26℃)”,”dayPictureUrl”:”http://api.map.baidu.com/images/weather/day/duoyun.png“,”nightPictureUrl”:”http://api.map.baidu.com/images/weather/night/xiaoyu.png“,”weather”:”多云转小雨”,”wind”:”南风微风”,”temperature”:”25 ~ 18℃”},{“date”:”周六”,”dayPictureUrl”:”http://api.map.baidu.com/images/weather/day/xiaoyu.png“,”nightPictureUrl”:”http://api.map.baidu.com/images/weather/night/xiaoyu.png“,”weather”:”小雨”,”wind”:”北风微风”,”temperature”:”23 ~ 17℃”},{“date”:”周日”,”dayPictureUrl”:”http://api.map.baidu.com/images/weather/day/duoyun.png“,”nightPictureUrl”:”http://api.map.baidu.com/images/weather/night/duoyun.png“,”weather”:”多云”,”wind”:”南风微风”,”temperature”:”26 ~ 15℃”},{“date”:”周一”,”dayPictureUrl”:”http://api.map.baidu.com/images/weather/day/duoyun.png“,”nightPictureUrl”:”http://api.map.baidu.com/images/weather/night/yin.png“,”weather”:”多云转阴”,”wind”:”南风微风”,”temperature”:”26 ~ 18℃”}]}]}

是很复杂吧,反正一开始看,就觉得这什么啊,简直太乱了,但是我们仔细的查看一下,发现这个还是有很清晰的结构的,无非数组里面有潜逃了几层对象嘛,话不多说,直接上代码吧。

package com.tiger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class TestSSDut {

public TestSSDut() {
// TODO Auto-generated constructor stub
}
public static String loadJson (String url) {
StringBuilder json = new StringBuilder();
try {
URL urlObject = new URL(url);
URLConnection uc = urlObject.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"utf-8"));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}

public static String JsonComplier(String jsonString) throws JSONException{

return null;
}

public static void main(String []args){
String json=loadJson("http://api.map.baidu.com/telematics/v3/weather?location=%E6%88%90%E9%83%BD&output=json&ak=rnm8udmHdWaHFWZTO2tuTiG8");
System.out.println(json);
String result;
try {
String str="";
JSONTokener jsonParser = new JSONTokener(json);
// 此时还未读取任何json文本,直接读取就是一个JSONObject对象。
// 如果此时的读取位置在"name" : 了,那么nextValue就是"yuanzhifei89"(String)
JSONObject person = (JSONObject) jsonParser.nextValue();
// 接下来的就是JSON对象的操作了
String error=person.getString("error");
String status=person.getString("status");
String date=person.getString("date");
str+="error="+error+"  status="+status+"  date="+date;
System.out.println(str);
JSONArray jsonArray=person.getJSONArray("results");
for(int i=0;i<jsonArray.length();i++){
String currentCity=jsonArray.getJSONObject(i).getString("currentCity");
System.out.println("currentCity="+currentCity);
String pm2_5=jsonArray.getJSONObject(i).getString("pm25");
System.out.println("pm2_5="+pm2_5);
JSONArray index=jsonArray.getJSONObject(i).getJSONArray("index");
for(int j=0;j<index.length();j++){
String title=index.getJSONObject(i).getString("title");
System.out.println(title);
String zs=index.getJSONObject(i).getString("zs");
System.out.println(zs);
String tipt=index.getJSONObject(i).getString("tipt");
System.out.println(tipt);
String des=index.getJSONObject(i).getString("des");
System.out.println(des);
}

JSONArray weather_data=jsonArray.getJSONObject(i).getJSONArray("weather_data");
for(int j=0;j<weather_data.length();j++){
String datee=weather_data.getJSONObject(i).getString("date");
System.out.println(datee);
String dayPictureUrl=weather_data.getJSONObject(i).getString("dayPictureUrl");
System.out.println(dayPictureUrl);
String nightPictureUrl=weather_data.getJSONObject(i).getString("nightPictureUrl");
System.out.println(nightPictureUrl);
String weather=weather_data.getJSONObject(i).getString("weather");
System.out.println(weather);
String wind=weather_data.getJSONObject(i).getString("wind");
System.out.println(wind);
String temperature=weather_data.getJSONObject(i).getString("temperature");
System.out.println(temperature);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public static List<String> getJsonArrayValue(String jsonString) throws JSONException{
JSONObject demoJson = new JSONObject();
JSONArray numberList = demoJson.getJSONArray(jsonString);
List<String>list=new ArrayList<String>();
for(int i=0; i<numberList.length(); i++){
//获取数组中的数组
list.add(String.valueOf(numberList.getJSONArray(i).getInt(0)));
}
return list;

}
}


下面是我解析出来的结果:

error=0  status=success  date=2015-10-16
currentCity=成都
pm2_5=173
穿衣
舒适
穿衣指数
建议着长袖T恤、衬衫加单裤等服装。年老体弱者宜着针织长袖衬衫、马甲和长裤。
周五 10月16日 (实时:26℃) http://api.map.baidu.com/images/weather/day/duoyun.png http://api.map.baidu.com/images/weather/night/xiaoyu.png
多云转小雨
南风微风
25 ~ 18℃
周五 10月16日 (实时:26℃) http://api.map.baidu.com/images/weather/day/duoyun.png http://api.map.baidu.com/images/weather/night/xiaoyu.png
多云转小雨
南风微风
25 ~ 18℃
周五 10月16日 (实时:26℃) http://api.map.baidu.com/images/weather/day/duoyun.png http://api.map.baidu.com/images/weather/night/xiaoyu.png
多云转小雨
南风微风
25 ~ 18℃
周五 10月16日 (实时:26℃) http://api.map.baidu.com/images/weather/day/duoyun.png http://api.map.baidu.com/images/weather/night/xiaoyu.png
多云转小雨
南风微风
25 ~ 18℃


解析出来的数据不是很全面。但我们还是来看一下这个思想吧。

我们一开始声明了一个JSONObject 名为person,这就是那个json字符串的最外边一层的key,接下来的操作需要依靠它来进行。对于解析过程,我们的思想就是:

1、对于直接的key我们可以直接获得对应的值,

2、对于对象,我们就需要借助JSONArray,来进行单独的处理,以获得所有的键值。

3、还有最重要的是,根据person获得的JsonObject 只能使用一次,对于对象里面的对象我们就需要使用该数组来再次获得一个数组,再对新的数组进行键值的处理即可。

好了,差不多就是这样了。本人能力有限,还望博友们多多提携,让我们一起进步吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: