java解析json

来源:互联网 发布:上海译文出版社淘宝店 编辑:程序博客网 时间:2024/06/15 04:16

解析json需要用到的包json-lib-2.1-jdk15.jar,下载地址http://download.csdn.net/detail/xionglangs/9449070

public static FerryForm analysisJson(String s) {

try {
/*
* s字符串必须是标准的json格式,要不然会报错,json格式
* "{‘class’:'1',‘students’:'[{‘name‘:’张三’,‘age’:‘12’,’sex‘:’男‘},{’name‘:’李四’,‘age‘:’13‘,’sex‘:‘女’}]‘}"
* ;一对大括号,前面明智,后面类容,用:隔开,后面用,隔开,一个json可以包含多个json值用[]包着
*/
FerryForm ferryForm = new FerryForm();
JSONObject jsonObject = JSONObject.fromObject(s);
String arrive = jsonObject.getString("ArriveSailingSpaces");
arrive = arrive.substring(1, arrive.length() - 1);
JSONObject jsonArrive = JSONObject.fromObject(arrive);
ArriveSailingSpaces arriveSailingSpaces = new ArriveSailingSpaces();
arriveSailingSpaces.setTerminalID(jsonArrive.getInt("TerminalID"));
arriveSailingSpaces.setTerminalName(jsonArrive
.getString("TerminalName"));
arriveSailingSpaces.setVesselId(jsonArrive.getInt("VesselId"));
arriveSailingSpaces.setVesselName(jsonArrive
.getString("VesselName"));
arriveSailingSpaces.setDisplayReservable(jsonArrive
.getString("DisplayReservable"));
if (jsonArrive.getString("ReservableInfo").equals("N/A")
|| jsonArrive.getString("ReservableInfo").equals(
"Unavailable")) {
arriveSailingSpaces.setReservableInfo("-1");
} else {
if (jsonArrive.getString("ReservableInfo").split(" Spaces").length == 1) {
arriveSailingSpaces.setReservableInfo(jsonArrive.getString(
"ReservableInfo").split(" Spaces")[0]);
}
if (jsonArrive.getString("ReservableInfo").split(" Space").length == 1) {
arriveSailingSpaces.setReservableInfo(jsonArrive.getString(
"ReservableInfo").split(" Space")[0]);
}
}
arriveSailingSpaces.setReservableHexColor(jsonArrive
.getString("ReservableHexColor"));
arriveSailingSpaces.setDisplayDriveUp(jsonArrive
.getString("DisplayDriveUp"));
arriveSailingSpaces.setDriveUpInfo(jsonArrive
.getString("DriveUpInfo"));
arriveSailingSpaces.setDriveUpHexColor(jsonArrive
.getString("DriveUpHexColor"));
arriveSailingSpaces.setMaxSpaceCount(jsonArrive
.getString("MaxSpaceCount"));
ferryForm.setArriveSailingSpaces(arriveSailingSpaces);
ferryForm.setCancelled(jsonObject.getBoolean("Cancelled"));
ferryForm.setDeparture(jsonObject.getString("Departure"));
ferryForm
.setDisplayDriveUp(jsonObject.getBoolean("DisplayDriveUp"));
ferryForm.setDisplayReservable(jsonObject
.getBoolean("DisplayReservable"));
ferryForm.setVessel(jsonObject.getString("Vessel"));
ferryForm.setVesselID(jsonObject.getInt("VesselID"));
return ferryForm;
} catch (Exception e) {
System.out.println(s);
System.out.println("Parse JSON error");
}
return null;

}


在JSONObject类中有个tobean方法,可以直接转化为类FerryForm ss = (FerryForm)JSONObject.toBean(jsonObject, FerryForm.class);用法。

0 0
原创粉丝点击