使用jackson 进行 xml、javaBean、json之间相互转换

一、pom依赖

        
            com.fasterxml.jackson.dataformat
            jackson-dataformat-xml
            2.9.1
        

二、实体类


import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlText;
import lombok.Data;

import java.util.Date;
import java.util.List;

@Data
@JacksonXmlRootElement(localName="Response")
public class RouteResponse {
    @JacksonXmlProperty(isAttribute = true, localName="service")
    private String service;
    @JacksonXmlProperty(isAttribute = true, localName="lang")
    private String lang;
    @JacksonXmlProperty(localName="Head")
    private String head;
    @JacksonXmlProperty(localName="Error")
    private Error error;
    @JacksonXmlProperty(localName="Body")
    private Body body;

    @Data
    public static class Error {
        @JacksonXmlProperty(isAttribute = true, localName="code") // 获取属性
        private String code;
        @JacksonXmlText // 获取结点文本内容
        private String msg;
    }

    @Data
    public static class Body {
        @JacksonXmlProperty(localName="WaybillRoute")
        private WaybillRoute waybillRoute;
    }

    @Data
    public static class WaybillRoute {
        @JacksonXmlProperty(isAttribute = true, localName="id")
        private String id;
        @JacksonXmlProperty(isAttribute = true, localName="remark")
        private String remark;
        @JacksonXmlElementWrapper(useWrapping =false)
        @JacksonXmlProperty(localName="Cargo")
        private List cargo;
        @JacksonXmlElementWrapper(localName ="Routes")
        @JacksonXmlProperty(localName ="Route")
        private List routes;
    }

    @Data
    public static class Cargo {
        @JacksonXmlProperty(isAttribute = true, localName="name")
        private String name;
        @JacksonXmlProperty(isAttribute = true, localName="price")
        private Double price;
    }

    @Data
    public static class Route {
        @JacksonXmlProperty(isAttribute = true, localName="address")
        private String address;
        @JacksonXmlProperty(isAttribute = true, localName="time")
        @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
        private Date time;
        @JacksonXmlText // 获取结点文本内容
        private String desc;
    }
}

三、Jackson工具类


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.util.Map;

public class JacksonUtils {

    /**
     * convert json to javabean or javabean to json.
     */
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * convert xml to javabean or javabean to xml.
     */
    private static XmlMapper xmlMapper = new XmlMapper();

    static {
        //反序列化时,若实体类没有对应的属性,是否抛出JsonMappingException异常,false忽略掉
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //忽略空属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

        //反序列化时,若实体类没有对应的属性,是否抛出JsonMappingException异常,false忽略掉
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //忽略空属性
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        xmlMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        //XML标签名:使用骆驼命名的属性名,
//        xmlMapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
        //设置转换模式
        xmlMapper.enable(MapperFeature.USE_STD_BEAN_NAMING);
    }

    /**
     * xmlStr convert to javaBean
     * @param xmlStr
     * @param clazz
     * @param 
     * @return
     * @throws JsonProcessingException
     */
    public static  T convertToBean(String xmlStr, Class clazz) throws JsonProcessingException {
        return xmlMapper.readValue(xmlStr,  clazz);
    }

    /**
     * javaBean convert to XmlStr
     * @param obj
     * @return
     * @throws JsonProcessingException
     */
    public static String convertToXmlStr(Object obj) throws JsonProcessingException {
        return "" + xmlMapper.writeValueAsString(obj);
    }

    /**
     * javaBean convert to jsonStr
     * @param obj
     * @return
     * @throws JsonProcessingException
     */
    public static String beanConvertToJson(Object obj) throws JsonProcessingException {
        return objectMapper.writeValueAsString(obj);
    }

    /**
     * jsonStr convert to javaBean
     * @param jsonStr
     * @param clazz
     * @param 
     * @return
     * @throws JsonProcessingException
     */
    public static  T jsonConvertToBean(String jsonStr, Class clazz) throws JsonProcessingException {
        return objectMapper.readValue(jsonStr, clazz);
    }

    /**
     * map convert to JsonString
     * @param map
     * @return
     * @throws JsonProcessingException
     */
    public static String mapConvertToJson(Map map) throws JsonProcessingException {
        return objectMapper.writeValueAsString(map);
    }

    /**
     * JsonString convert to Map
     * @param jsonStr
     * @return
     * @throws JsonProcessingException
     */
    public static Map jsonConvertToMap(String jsonStr) throws JsonProcessingException {
        return objectMapper.readValue(jsonStr, Map.class);
    }
}

四、单测 使用示例


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class RouteResponseTest {

    private String jsonStr;
    private Map map;

    @Test
    public void convertToBeanTest() throws JsonProcessingException {
        // 1.设置xmlStr
        String xmlStr = getXmlStr();
        System.out.println("xmlStr:"+ xmlStr);
        // 2.xml -> bean
        RouteResponse routeResponse = JacksonUtils.convertToBean(xmlStr, RouteResponse.class);

        // 3.设置日期
        List routes = routeResponse.getBody().getWaybillRoute().getRoutes();
        for (RouteResponse.Route route : routes) {
            route.setTime(new Date());
        }
        System.out.println("routeResponse:" +routeResponse);

        // bean -> jsonStr
        String jsonStr = JacksonUtils.beanConvertToJson(routeResponse);
        System.out.println("jsonStr:"+ jsonStr);

        // jsonStr -> map
        Map map = JacksonUtils.jsonConvertToMap(jsonStr);
        System.out.println("map:"+ map);

        // map -> jsonStr
        String toJson = JacksonUtils.mapConvertToJson(map);
        System.out.println("toJson:"+ toJson);

        // jsonStr -> bean
        RouteResponse response = JacksonUtils.jsonConvertToBean(jsonStr, RouteResponse.class);
        System.out.println(JSON.toJSONString(response));
        
    }
    
    /**
     *
     *     OK
     *     发送成功,ok...
     *     
     *         
     *             
     *             
     *             
     *                 下单
     *                 揽件
     *                 签收
     *             
     *         
     *     
     * 
     * @return
     */
    private String getXmlStr() {
        return    ""
                + "OK"
                + "发送成功,ok..."
                + ""
                + ""
                + ""
                + ""
                + ""
                + "下单"
                + "揽件"
                + "签收"
                + ""
                + ""
                + ""
                + "";
    }
}

 

你可能感兴趣的:(使用jackson 进行 xml、javaBean、json之间相互转换)