net.sf.json的使用
需要jar包:ezmorph-1.0.6.jar,json-lib-2.3.jar
创建java对象:
public class Address {
private String road;
private String streate;
private String provience;
private String no;
public String getRoad() {
return road;
}
public void setRoad(String road) {
this.road = road;
}
public String getStreate() {
return streate;
}
public void setStreate(String streate) {
this.streate = streate;
}
public String getProvience() {
return provience;
}
public void setProvience(String provience) {
this.provience = provience;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
}
1.将json对象转化为java对象
JSONObject jsonObject = JSONObject.fromObject("{\"no\":\"104\",\"provience\":\"陕西\",\"road\":\"高新路\",\"streate\":\"\"}");
Address Address = (Address) JSONObject.toBean(jsonObject,Address.class);
log.info(Address.getNo());
log.info(Address.getStreate());
log.info(Address.getProvience());
log.info(Address.getRoad());
2.将java对象转化为json对象
将java对象转化为json对象:
Address address = new Address();
address.setNo("104");
address.setProvience("陕西");
address.setRoad("高新路");
address.setStreate("");
JSONArray json = JSONArray.fromObject(address);
log.info(json.toString());
将java对象list转化为json对象:
Address address = new Address();
address.setNo("104");
address.setProvience("陕西");
address.setRoad("高新路");
address.setStreate("");
Address address2 = new Address();
address2.setNo("105");
address2.setProvience("陕西");
address2.setRoad("未央路");
address2.setStreate("张办");
List list = new ArrayList();
list.add(address);
list.add(address2);
JSONArray json = JSONArray.fromObject(list);
log.info(json.toString());
3.JSONArray转化为list
JSONObject jsonObject = JSONObject.fromObject("{\"no\":\"104\",\"provience\":\"陕西\",\"road\":\"高新路\",\"streate\":\"\"}");
JSONArray jsonArray = new JSONArray();
jsonArray.add("{\"no\":\"104\",\"provience\":\"陕西\",\"road\":\"高新路\",\"streate\":\"\"}");
jsonArray.add("{\"no\":\"104\",\"provience\":\"陕西\",\"road\":\"高新路\",\"streate\":\"123\"}");
Object object = JSONArray.toList(jsonArray,Address.class);
摘自 rommel1的专栏
补充:Web开发 , 其他 ,