您的位置 首页 java

JSON与XML互相转化(Jackson)

JSON与XML互相转化(Jackson)

选型: json-lib.jar可以做,但是太老了,抛弃; fast JSON 完全没有xml相关功能; staxon经测试不能用。 最终选用jackson来主要实现。

JDK为1.8,如果低于1.8,则只需要将try-catch的语法改回传统书写方式。

目前的实现,传参和回参都是String,如果想JSONObject对象和XML对象互转,只需要再包一层就可以多2个或4个方法。

一、依赖

pom.xml

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-core</artifactId>

<version>2.8.8</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.8.8</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.dataformat</groupId>

<artifactId>jackson-dataformat-xml</artifactId>

<version>2.8.8</version>

</dependency>

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<vers io n>1.2.33</version>

</dependency>

二、实现

package com.kapu.common.utility;

import java.io.IOException;

import java.io.StringWriter;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson. json ;

import com.alibaba.fastjson.JSONObject;

import com.fasterxml.jackson.core.JsonGenerator;

import com.fasterxml.jackson.core.JsonParseException;

import com.fasterxml.jackson.core.JsonParser;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class JsonXmlUtil {

private static final String XML_PREFIX = “<?xml version=”1.0″ encoding=”UTF-8″ ?>”;

private static final String XML_PREFIX_HEAD = “<?”;

private static final String XML_PREFIX_TAIL = “?>”;

private static final String XML_ROOT_START = “<xml>”;

private static final String XML_ROOT_END = “</xml>”;

/**

* json string convert to xml string

* @throws IOException

* @throws JsonParseException

*/

public static String json2xml(String json) throws IOException {

if (StringUtils.isEmpty(json)) {

return null;

}

JSONObject jsonObject = JSON.parseObject(json);

StringWriter w = new StringWriter();

XmlMapper xmlMapper = new XmlMapper();

xmlMapper.writeValue(w, jsonObject);

String xml = w. toString ();

xml = xml.replaceAll(“<JSONObject>”, “”).replaceAll(“</JSONObject>”, “”);

xml = XML_PREFIX + xml;

return xml;

}

/**

* xml string convert to json string

* @throws IOException

*/

public static String xml2json(String xml) throws IOException {

if(StringUtils.isEmpty(xml)) {

return null;

}

if(xml.indexOf(XML_PREFIX_HEAD) > -1 && xml.indexOf(XML_PREFIX_TAIL) > -1){

xml = xml.substring(xml.indexOf(XML_PREFIX_TAIL) + 2);

}

xml = XML_ROOT_START + xml + XML_ROOT_END;

StringWriter w = new StringWriter();

try(JsonParser jp = new XmlMapper().getFactory().createParser(xml);JsonGenerator jg = new ObjectMapper().getFactory().createGenerator(w);){

while (jp.nextToken() != null) {

jg.copyCurrentEvent(jp);

}

}

return w.toString();

}

}

三、测试

package com.kapu.common.base;

import java.io.IOException;

import org.junit.Test;

import com.kapu.common.utility.JsonXmlUtil;

import com.alibaba.fastjson.JSONObject;

public class JsonXml {

@Test

public void testJson2Xml() {

JSONObject meta = new JSONObject();

meta.put(“from”, “WEB”);

meta.put(“token”, “sdfa4sdf4as5d4f8a4sd8f4asdf”);

meta.put(“timestamp”, System.currentTimeMillis());

JSONObject data = new JSONObject();

data.put(“id”, 123);

data.put(“name”, “one-two-three”);

data.put(“desc”, “this is a number list”);

JSONObject json = new JSONObject();

json.put(“meta”, meta);

json.put(“data”, data);

json.put(” aaa “, “aaaaaa”);

System.out.println(json);

String xml = null;

try {

xml = JsonXmlUtil.json2xml(json.toJSONString());

} catch (Throwable e) {

e.printStackTrace();

}

System.out.println(xml);

}

@Test

public void testXml2Json() {

String xml = “<?xml version=”1.0″ encoding=”UTF-8″ ?><aaa>aaaaaa</aaa><data><name>one-two-three</name> <id>123</id><desc>thisisanumberlist</desc></data><meta><from>WEB</from><token>sdfa4sdf4as5d4f8a4sd8f4asdf</token><timestamp>1536049559684</timestamp></meta>”;

try {

String json = JsonXmlUtil.xml2json(xml);

System.out.println(json);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

@Test

public void testJson2Xml2Json() throws IOException {

JSONObject meta = new JSONObject();

meta.put(“from”, “WEB”);

meta.put(“token”, “sdfa4sdf4as5d4f8a4sd8f4asdf”);

meta.put(“timestamp”, System.currentTimeMillis());

JSONObject data = new JSONObject();

data.put(“id”, 123);

data.put(“name”, “one-two-three”);

data.put(“desc”, “this is a number list”);

JSONObject json = new JSONObject();

json.put(“meta”, meta);

json.put(“data”, data);

json.put(“aaa”, “aaaaaa”);

System.out.println(json.toJSONString());

String xml = JsonXmlUtil.json2xml(json.toJSONString());

System.out.println(xml);

String jsonStr = JsonXmlUtil.xml2json(xml);

System.out.println(jsonStr);

}

}

文章来源:智云一二三科技

文章标题:JSON与XML互相转化(Jackson)

文章地址:https://www.zhihuclub.com/185428.shtml

关于作者: 智云科技

热门文章

评论已关闭

3条评论

  1. 2002; Vilatoba et al She experienced weight loss, hair loss, difficulty sleeping, suicidal thoughts and chest pain

  2. I have changed many things to improve my sleep, and although I don t have all of the answers, I have figured out a few things that might help you mirapex abilify cold turkey A crackdown on commercial bribery by multinationals isdeeply significant to safeguarding the order of the marketeconomy and protecting an environment of fair competition, saidthe commentary in the mouthpiece of the ruling Communist Party

网站地图