有关JSON的工具类有很多,都很方便,用过Gson和fastjson,以及最近使用json-lib
一.Object转为Json,生成json
单个对象Object:
Address addr = new Address();
addr.setState("四川");
addr.setCity("成都");
List,Array,Map,Set类型都是同样的方法,简单统一
Gson:
String json = gson.toJson(addr);
FastJson:
String json = JSON.toJSONString(addr);
Json-Lib:
JSONObject json = JSONObject.fromObject(addr);
具体代码:
//bean---->json
Address addr = new Address();
addr.setState("四川");
addr.setCity("成都");
JSONObject jsonObj = JSONObject.fromObject(addr);
System.out.println("jsonObj:"+jsonObj);
//集合-->JSONArray
Set<Address> set = new HashSet<Address>();
Address[] addrArray = new Address[2];
List<Address> list = new ArrayList<Address>();
Map<String,Object> map=new HashMap<>();
for(int i=0;i<2;i++){
Address address = new Address();
address.setState("四川");
address.setCity("成都");
list.add(address);
addrArray[i]=address;
set.add(address);
map.put("add"+i,address);
}
JSONArray jsonList = JSONArray.fromObject(list);
JSONArray jsonArray = JSONArray.fromObject(addrArray);
JSONArray jsonSet = JSONArray.fromObject(set);
JSONArray jsonMap = JSONArray.fromObject(map);
结果:
jsonObj:{"city":"成都","state":"四川"}
jsonList:[{"city":"成都","state":"四川"},{"city":"成都","state":"四川"}]
jsonArray:[{"city":"成都","state":"四川"},{"city":"成都","state":"四川"}]
jsonSet:[{"city":"成都","state":"四川"},{"city":"成都","state":"四川"}]
jsonMap:[{"add0":{"city":"成都","state":"四川"},"add1":{"city":"成都","state":"四川"}}]
二.Json转Object,解析json
Json数据:
String jsonStr = "{\"city\":\"成都\",\"state\":\"四川\"}";
String jsonMapStr = "[{\"add0\":{\"city\":\"成都\",\"state\":\"四川\"},\"add1\":{\"city\":\"成都\",\"state\":\"四川\"}}]";
String bigJsonStr = "{\"add0\":{\"city\":\"成都\",\"state\":\"四川\"},\"add1\":{\"city\":\"成都\",\"state\":\"四川\"}}";
Gson:
Gson gson = new Gson;
Address address=gson.fromJson(jsonStr, Address.class);
FastJson:
Address address = JSON.parseObject(jsonStr, Address.class);
Json-Lib:
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
Address address = (Address) JSONObject.toBean(jsonObject, Address.class);
上面这些是将json装载到自己的实体类里面,json-lib还可以直接使用json,特别是可以直接转发或者存json的时候用,所以我觉得很方便:
JSONObject jsonObject = JSONObject.fromObject(bigJsonStr);
JSONObject add0= (JSONObject) jsonObject.get("add0");
String city= (String) add0.get("city");
结果:
city:成都