jackson json-lib配合完成xml json互换
前段时间优化性能,将原来用的json-lib转换为了jackson,现在要解析xml,发现jaconson解析xml有问题,它对数组元素直解析最后一个,真不知是出于什么考虑?
而json-lib则没有这个问题,但是json-lib输出的json格式有些多余的双引号转义,不是很标准,它生成的json是无法让jackson解析的。
尝试了xstream,要自己写代码解析,不能用。
最后只好两个结合起来用:
public static Map<String,Object> parseXml(String xml){ try { xml = xml.replaceAll(">\s+<", "><"); JSON json1 = (new XMLSerializer()).read(xml); String resoult = null; Map<String,Object> map = null; if(json1.isArray()) { JSONArray jsonarray = (JSONArray)json1; map = (Map<String,Object>)jsonarray.get(0); }else{ map = (Map<String,Object>)json1; } return map; } catch (Exception e) { throw ExceptionUtils.silence(e); } }
转换为map后就好说了,再用jackson来转换为string
public static String toJsonString(Object obj) { if (null == obj) { return "null"; } StringWriter writer = new StringWriter(); ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(writer, obj); } catch (Exception e) { throw ExceptionUtils.silence(e); } return writer.toString(); }
maven依赖:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>