Java中xml2json,json2xml

在JAVA中xml与json数据互相转换

package com.sgcc.platform.common.utils;

import static java.lang.String.format;

import java.util.Map;

import org.json.JSONObject;
import org.json.XML;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.sgcc.platform.common.exceptions.ConvertException;

/**
 * json,xml互相转换
 * @author libing
 *
 */
public class JsonXmlUtil {
    private static JacksonXmlModule module = new JacksonXmlModule();
    private static ObjectMapper objectMapper = new ObjectMapper(); 
    private static XmlMapper xmlMapper = new XmlMapper(module);
    static{
        //去掉xml顶部内容<?xml version="1.0" encoding="UTF-8" ?>
        module.setDefaultUseWrapper(false);
    }
    
    /**
     * xml字符串转换成net.sf.json.JSONObject对象
     * @param xmlStr
     * @return
     */
    public static JSONObject xml2jsonObj(String xmlStr){
        JSONObject jsonObject = XML.toJSONObject(xmlStr);
        return jsonObject;
    }
    
    /**
     * xml字符串转换成json字符串
     * @param xmlStr
     * @return
     */
    public static String xml2jsonStr(String xmlStr){
        JSONObject jsonObject = XML.toJSONObject(xmlStr);
        return jsonObject.toString();
    }
    
    /**
     * json字符串转换成xml字符串
     * @param jsonStr
     * @return
     */
    public static String json2xml(String jsonStr){
        try {
            JsonNode root = objectMapper.readTree(jsonStr);
            String result = xmlMapper.writeValueAsString(root);
            return result.replaceAll("</?ObjectNode>","");
        } catch (Exception e) {
            throw new ConvertException(format("incorrect JSON data:/n%s",jsonStr));
        }
    }
    
    /**
     * map数据转换成xml字符串
     * @param mapData
     * @return
     */
    public static String map2xml(Map<String,Object> mapData){
        Object repinfoJsonObj = JSONObject.wrap(mapData);
        String jsonStr=repinfoJsonObj.toString();
        String result=json2xml(jsonStr);
        return result;
    }
    
//    public static void main(String[] args) throws Exception {
//        String ss="{\"REPINFO\":{\"SITEDATA\":[{\"SITE_NAME\":\"有没 \",\"REMARK\":null,\"MEASCODE\":35,\"SITE_ID\":2},{\"SITE_NAME\":\"城\",\"REMARK\":null,\"MEASCODE\":35,\"SITE_ID\":3}]}}";
//        System.out.println(json2xml(ss));
//        
//    }
}

 

posted @ 2016-04-27 15:21  业精于勤而荒于嬉  阅读(2080)  评论(0编辑  收藏  举报