json-lib最开始的也是应用最广泛的json解析工具,json-lib 不好的地方确实是依赖于很多第三方包,包括commons-beanutils.jar,commons-collections-3.2.jar,commons-lang-2.6.jar,commons-logging-1.1.1.jar,ezmorph-1.0.6.jar,对于复杂类型的转换,json-lib对于json转换成bean还有缺陷,比如一个类里面会出现另一个类的list或者map集合,json-lib从json到bean的转换就会出现问题。json-lib在功能和性能上面都不能满足现在互联网化的需求。
相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。Jackson对于复杂类型的json转换bean会出现问题,一些集合Map,List的转换出现问题。Jackson对于复杂类型的bean转换Json,转换的json格式不是标准的Json格式
Gson是目前 功能最全的Json解析神器,Gson当初是为因应Google公司内部需求而由Google自行研发而来,但自从在2008年五月公开发布第一版后已被许多公司或用户应用。Gson的 应用主要为toJson与fromJson两个转换函数,无依赖,不需要例外额外的jar,能够直接跑在JDK上。而在使用这种对象转换之前需先创建好对象的类型以及其成员才能成功的将JSON字符串成功转换成相对应的对象。类里面只要有get和set方法,Gson完全可以将复杂类型的json到bean或bean到json的转换,是JSON解析的神器。Gson在功能上面无可挑剔,但是性能上面比FastJson有所差距。
Fastjson是一个Java语言编写的 高性能的JSON处理器,由阿里巴巴公司开发。无依赖,不需要例外额外的jar,能够直接跑在JDK上。FastJson在复杂类型的 Bean转换Json上会出现一些问题,可能会出现引用的类型,导致Json转换出错,需要制定引用。FastJson采用独创的算法, 将parse的速度提升到极致,超过所有json库。
Gson类:解析json的最基础的工具类JsonParser类:解析器来 解析JSON到JsonElements的解析树JsonElement类:一个 类代表的JSON元素JsonObject类:JSON对象类型JsonArray类:JsonObject数组TypeToken类:用于创建type,比如泛型List<?>
com.google.code.gsongson2.2.4
public class Book{ private String id; private String name; public Book() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Student{ private String name; private int age; private String sex; private String describe; private Set books; public Student() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Set getBooks() { return books; } public void setBooks(Set books) { this.books = books; } public String getDescribe() { return describe; } public void setDescribe(String describe) { this.describe = describe; } }
Gson gson = new Gson(); String json = gson.toJson(obj); obj是对象
Gson gson = new Gson(); String json = "{\"id\":\"2\",\"name\":\"Json技术\"}"; Book book = gson.fromJson(json, Book.class);
将json转换成复杂类型的bean,需要使用TypeTokenGson gson = new Gson(); String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]"; //将json转换成List List list = gson.fromJson(json,new TypeToken<LIST>() {}.getType()); //将json转换成Set Set set = gson.fromJson(json,new TypeToken<SET>() {}.getType());
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]"; Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(json); json = gson.toJson(je);
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]"; boolean jsonFlag; try { new JsonParser().parse(str).getAsJsonObject(); jsonFlag = true; } catch (Exception e) { jsonFlag = false; }
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; String propertyName = 'id'; String propertyValue = ""; try { JsonParser jsonParser = new JsonParser(); JsonElement element = jsonParser.parse(json); JsonObject jsonObj = element.getAsJsonObject(); propertyValue = jsonObj.get(propertyName).toString(); } catch (Exception e) { propertyValue = null; }
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; String propertyName = 'id'; JsonParser jsonParser = new JsonParser(); JsonElement element = jsonParser.parse(json); JsonObject jsonObj = element.getAsJsonObject(); jsonObj.remove(propertyName); json = jsonObj.toString();
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; String propertyName = 'desc'; Object propertyValue = "json各种技术的调研"; JsonParser jsonParser = new JsonParser(); JsonElement element = jsonParser.parse(json); JsonObject jsonObj = element.getAsJsonObject(); jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue)); json = jsonObj.toString();
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; String propertyName = 'name'; Object propertyValue = "json各种技术的调研"; JsonParser jsonParser = new JsonParser(); JsonElement element = jsonParser.parse(json); JsonObject jsonObj = element.getAsJsonObject(); jsonObj.remove(propertyName); jsonObj.addProperty(propertyName, new Gson().toJson(propertyValue)); json = jsonObj.toString();
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; String propertyName = 'name'; boolean isContains = false ; JsonParser jsonParser = new JsonParser(); JsonElement element = jsonParser.parse(json); JsonObject jsonObj = element.getAsJsonObject(); isContains = jsonObj.has(propertyName);
GsonBuilder builder = new GsonBuilder(); builder.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Gson gson = builder.create(); 然后使用gson对象进行json的处理,如果出现日期Date类的对象,就会按照设置的格式进行处理
三、阿里巴巴的FastJson包的使用简介。Gson gson = new Gson(); 这种对象默认对Html进行转义,如果不想转义使用下面的方法 GsonBuilder builder = new GsonBuilder(); builder.disableHtmlEscaping(); Gson gson = builder.create();
com.alibabafastjson1.1.22
将对象转换成格式化的json JSON.toJSONString(obj,true); 将对象转换成非格式化的json JSON.toJSONString(obj,false); obj设计对象 对于复杂类型的转换,对于重复的引用在转成json串后在json串中出现引用的字符,比如 $ref":"$[0].books[1] Student stu = new Student(); Set books= new HashSet(); Book book = new Book(); books.add(book); stu.setBooks(books); List list = new ArrayList(); for(int i=0;i<5;i++) list.add(stu); String json = JSON.toJSONString(list,true);
String json = "{\"id\":\"2\",\"name\":\"Json技术\"}"; Book book = JSON.parseObject(json, Book.class);
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]"; //将json转换成List List list = JSON.parseObject(json,new TypeReference<ARRAYLIST>(){}); //将json转换成Set Set set = JSON.parseObject(json,new TypeReference<HASHSET>(){});
String propertyName = 'id'; String propertyValue = ""; String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; JSONObject obj = JSON.parseObject(json); propertyValue = obj.get(propertyName));
String propertyName = 'id'; String propertyValue = ""; String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; JSONObject obj = JSON.parseObject(json); Set set = obj.keySet(); propertyValue = set.remove(propertyName); json = obj.toString();
String propertyName = 'desc'; Object propertyValue = "json的玩意儿"; String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; JSONObject obj = JSON.parseObject(json); obj.put(propertyName, JSON.toJSONString(propertyValue)); json = obj.toString();
String propertyName = 'name'; Object propertyValue = "json的玩意儿"; String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; JSONObject obj = JSON.parseObject(json); Set set = obj.keySet(); if(set.contains(propertyName)) obj.put(propertyName, JSON.toJSONString(propertyValue)); json = obj.toString();
String propertyName = 'name'; boolean isContain = false; String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; JSONObject obj = JSON.parseObject(json); Set set = obj.keySet(); isContain = set.contains(propertyName);
Object obj = new Date(); String json = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss.SSS"); 使用JSON.toJSONStringWithDateFormat,该方法可以使用设置的日期格式对日期进行转换
net.sf.json-libjson-libjdk152.2.2
commons-beanutils1.8.3commons-collections3.2commons-lang2.6commons-logging1.1.1net.sf.ezmorphezmorph1.0.6
同上
String json = JSONObject.fromObject(obj).toString();
String json = JSONArray.fromObject(list).toString(); String json = JSONArray.fromObject(map).toString();
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}"; JSONObject jsonObj = JSONObject.fromObject(json); Book book = (Book)JSONObject.toBean(jsonObj,Book.class);
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"Java技术\"}]"; JSONArray jsonArray = JSONArray.fromObject(json); JSONObject jsonObject; T bean; int size = jsonArray.size(); List list = new ArrayList(size); for (int i = 0; i < size; i++) { jsonObject = jsonArray.getJSONObject(i); bean = (T) JSONObject.toBean(jsonObject, beanClass); list.add(bean); }
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}"; JSONObject jsonObject = JSONObject.fromObject(jsonString); Iterator keyIter = jsonObject.keys(); String key; Object value; Map valueMap = new HashMap(); while (keyIter.hasNext()) { key = (String) keyIter.next(); value = jsonObject.get(key).toString(); valueMap.put(key, value); }
创建转换的接口实现类,转换成指定格式的日期class DateJsonValueProcessor implements JsonValueProcessor{ public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS"; private DateFormat dateFormat; public DateJsonValueProcessor(String datePattern) { try { dateFormat = new SimpleDateFormat(datePattern); } catch (Exception ex) { dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN); } } public Object processArrayValue(Object value, JsonConfig jsonConfig) { return process(value); } public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { return process(value); } private Object process(Object value) { return dateFormat.format[1]; Map<STRING,DATE> birthDays = new HashMap<STRING,DATE>(); birthDays.put("WolfKing",new Date()); JSONObject jsonObject = JSONObject.fromObject(birthDays, jsonConfig); String json = jsonObject.toString(); System.out.println(json); } }
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}"; Object key = "name"; Object value = null; JSONObject jsonObject = JSONObject.fromObject(jsonString); value = jsonObject.get(key); jsonString = jsonObject.toString();
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}"; Object key = "name"; Object value = null; JSONObject jsonObject = JSONObject.fromObject(jsonString); value = jsonObject.remove(key); jsonString = jsonObject.toString();
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}"; Object key = "desc"; Object value = "json的好东西"; JSONObject jsonObject = JSONObject.fromObject(jsonString); jsonObject.put(key,value); jsonString = jsonObject.toString();
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}"; boolean containFlag = false; Object key = "desc"; JSONObject jsonObject = JSONObject.fromObject(jsonString); containFlag = jsonObject.containsKey(key);
Gson gson = new Gson(); gson.fromJson(data, Person.class); //data 为 String类型
JSONObject jsonObject=new JSONObject(data); //data 为 String类型 String result = jsonObject.getString("Result");
Gson gson = new Gson(); String str = gson.toJson(person); //person 为 Person对象
JSONObject jsonObject=new JSONObject(); jsonObject.put(String name, xx value);
从InputStream中读取到String:(使用下面的服务器对应方法会出现出错) String resultStr = ""; InputStream inStrm = httpUrlConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(inStrm); BufferedReader bufferReader = new BufferedReader(isr); String inputLine = ""; while((inputLine = bufferReader.readLine()) != null){ resultStr += inputLine; } 向OutputStream写入String: String value = ""; OutputStream outStrm = httpUrlConnection.getOutputStream(); ObjectOutputStream objOutputStrm = new ObjectOutputStream(outStrm); objOutputStrm.writeObject(value); //value是String类型 objOutputStrm.flush(); objOutputStrm.close();
从InputStream中读取到String:(使用前面的安卓机对应方法会出现出错) String resultStr = ""; InputStream inStrm = request.getInputStream(); //request是HttpServletRequest类型 ObjectInputStream objIn = new ObjectInputStream(inStrm); try { resultStr = (String)objIn.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } 向OutputStream写入String: PrintWriter out = response.getWriter(); //response是HttpServletResponse类型 out.println(string); //string 是 String 类型 out.flush(); out.close();