Java Json xml 格式之间转换(一)

  • Post author:
  • Post category:java


实现json转map map转xml

记录dom4j  gson实现记录
记录参数配置
基础参数  id、name
数组参数 arr
含有属性的基础参数 po.id
属性参数和命令空间参数: -xmlns    #text表示 基础参数含有属性值需要配置值字段
根元素: root

实现 xml中标签属性的插入 和命令空间属性的插入

测试xml报文如下

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <root xmlns="sss">
        <arr>
            <name>ca</name>
            <id>1</id>
        </arr>
        <arr>
            <name>cs</name>
            <id>2</id>
        </arr>
        <id>1</id>
        <po>
            <id xml="sasd">1</id>
            <code>AD123</code>
        </po>
    </root>
</root>


json转map 方法

public static Map<String, Object> json2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        if(jsonStr != null && !"".equals(jsonStr)){
            //最外层解析
            try {
                Map jsonObject = objectMapper.readValue(jsonStr, Map.class);
                for (Object k : jsonObject.keySet()) {
                    Object v = jsonObject.get(k);
                    //如果内层还是数组的话,继续解析
                    if (v instanceof ArrayList) {
                        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                        Iterator<Map> it = ((ArrayList) v).iterator();
                        while (it.hasNext()) {
                            Map json2 = it.next();
                            list.add(json2Map(objectMapper.writeValueAsString(json2)));
                        }
                        map.put(k.toString(), list);
                    } else {
                        map.put(k.toString(), v);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return map;
        }else{
            return null;
        }
    }

map转xml

public static String jsonToXml(Object json, String rootKey) {
    Document document = DocumentHelper.createDocument();
    //设置根节点和命名空间
    QName qName = new QName(rootKey);
    //设置命令空间
    Element element = document.addElement(qName);
    document.setRootElement(element);

    ObjectMapper objectMapper = new ObjectMapper();
    try {
        JsonObject jsonObject = new JsonParser().parse(objectMapper.writeValueAsString(json)).getAsJsonObject();
        toXml(jsonObject, document.getRootElement(), null);
        return document.asXML();
    } catch (Exception e) {
        log.error(e.getMessage());
        throw new AppException(e.getMessage());
    }
}

private static Element toXml(JsonElement jsonElement, Element parentElement, String name) {
    if (jsonElement instanceof JsonArray) {
        //是json数据,需继续解析
        JsonArray sonJsonArray = (JsonArray)jsonElement;
        for (int i = 0; i < sonJsonArray.size(); i++) {
            JsonElement arrayElement = sonJsonArray.get(i);
            toXml(arrayElement, parentElement, name);
        }
    }else if (jsonElement instanceof JsonObject) {
        //说明是一个json对象字符串,需要继续解析
        JsonObject sonJsonObject = (JsonObject) jsonElement;
        Element currentElement = null;
        if (name != null) {
            currentElement = parentElement.addElement(name);
        }
        Set<Map.Entry<String, JsonElement>> set = sonJsonObject.entrySet();
        for (Map.Entry<String, JsonElement> s : set) {
            toXml(s.getValue(), currentElement != null ? currentElement : parentElement, s.getKey());
        }
    }else if (jsonElement.isJsonNull()){
        parentElement.addElement(name);
    }else {
        //说明是一个键值对的key,可以作为节点插入了
        addAttribute(parentElement, name, jsonElement.getAsString());
    }
    return parentElement;
}

private static void addAttribute(Element element, String name, String value) {
    //增加子节点,并为子节点赋值
    if (String.valueOf(name.charAt(0)).equals(StringPool.DASH)){

        // 参数前为 “-”符号的为节点属性 去除“-”符号并添加属性
        String key=name.substring(1);
        if (key.equals("xmlns")){
            Namespace namespace=new Namespace("",value);
            QName qName=new QName(element.getName(),namespace);
            element.setQName(qName);
        }else {
            element.addAttribute(key,value);
        }
    }else if (StringPool.HASH.equals(String.valueOf(name.charAt(0)))){
        element.addText(value);
    }else {
        Element el = element.addElement(name);
        el.addText(value);
    }
}

在这里插入图片描述


json-lib实现xml转json 转换根节点为顶级对象


json-lib 如果需要转换json后没有根节点ForceTopLevelObject设为false 反之true

某些场景xml转json后会默认存在o顶级对象节点可以设为false

String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
              "<TRN_RESULT xms=\"saasdasd\" xmlns:ceb=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
              "  <CUS_CIQ_NO>I20170000000020464</CUS_CIQ_NO>\n" +
              "  <SP_TRN_SEQ_NO>T11000000075628798</SP_TRN_SEQ_NO>\n" +
              "  <TRANS_DCL_NO>1701010106500000</TRANS_DCL_NO>\n" +
              "<BILL_NO>2222</BILL_NO>\n" +
              "  <RESULT_NTC_DATE>20170612</RESULT_NTC_DATE>\n" +
              "  <PROC_RESULT>L</PROC_RESULT>\n" +
              "  <NOTE>海关入库成功</NOTE>\n" +
              "</TRN_RESULT>";
      XMLSerializer xmlSerializer = new XMLSerializer();
      // ForceTopLevelObject默认为false
      System.out.println(xmlSerializer.isForceTopLevelObject());
      xmlSerializer.setForceTopLevelObject(true);
      InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));

      JSON json = xmlSerializer.readFromStream(stream);
      System.out.println(json.toString());

在这里插入图片描述

额外记录


mybatisplus StringPool常用符号常量

String AMPERSAND = "&";
    String AND = "and";
    String AT = "@";
    String ASTERISK = "*";
    String STAR = "*";
    String BACK_SLASH = "\\";
    String COLON = ":";
    String COMMA = ",";
    String DASH = "-";
    String DOLLAR = "$";
    String DOT = ".";
    String DOTDOT = "..";
    String DOT_CLASS = ".class";
    String DOT_JAVA = ".java";
    String DOT_XML = ".xml";
    String EMPTY = "";
    String EQUALS = "=";
    String FALSE = "false";
    String SLASH = "/";
    String HASH = "#";
    String HAT = "^";
    String LEFT_BRACE = "{";
    String LEFT_BRACKET = "(";
    String LEFT_CHEV = "<";
    String DOT_NEWLINE = ",\n";
    String NEWLINE = "\n";
    String N = "n";
    String NO = "no";
    String NULL = "null";
    String OFF = "off";
    String ON = "on";
    String PERCENT = "%";
    String PIPE = "|";
    String PLUS = "+";
    String QUESTION_MARK = "?";
    String EXCLAMATION_MARK = "!";
    String QUOTE = "\"";
    String RETURN = "\r";
    String TAB = "\t";
    String RIGHT_BRACE = "}";
    String RIGHT_BRACKET = ")";
    String RIGHT_CHEV = ">";
    String SEMICOLON = ";";
    String SINGLE_QUOTE = "'";
    String BACKTICK = "`";
    String SPACE = " ";
    String TILDA = "~";
    String LEFT_SQ_BRACKET = "[";
    String RIGHT_SQ_BRACKET = "]";
    String TRUE = "true";
    String UNDERSCORE = "_";
    String UTF_8 = "UTF-8";
    String US_ASCII = "US-ASCII";
    String ISO_8859_1 = "ISO-8859-1";
    String Y = "y";
    String YES = "yes";
    String ONE = "1";
    String ZERO = "0";
    String DOLLAR_LEFT_BRACE = "${";
    String HASH_LEFT_BRACE = "#{";
    String CRLF = "\r\n";
    String HTML_NBSP = "&nbsp;";
    String HTML_AMP = "&amp";
    String HTML_QUOTE = "&quot;";
    String HTML_LT = "&lt;";
    String HTML_GT = "&gt;";
    String[] EMPTY_ARRAY = new String[0];
    byte[] BYTES_NEW_LINE = "\n".getBytes();

后记


Java Json xml 格式之间转换(二) xml报文转java 、json 单标签转json数组处理



版权声明:本文为END_Loving原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。