欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

fastjson和jackson JSON转换实践

程序员文章站 2022-07-12 22:17:03
...

        在实际开发过程,需将请求第三方返回的JSON串转成JAVA对象,用fastjson发现,如果JAVA对象中缺少JSON串的key,将不能正常转换,将会报报Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "amount"之类的异常。当然可以补全JAVA对象中属性,但毕竟是第三方返回的JSON串,以后第三方如果再增加新的key那也必须同时修改我们的JAVA对象,就强依赖了。于是用jackson工具,发现无此问题。

        下面是测试验证的完整代码:

UserDTO.java

package com.bijian.test;

public class UserDTO {

    private String name;
    private int age;
    private String city;
    private String grade;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
    
    @Override
    public String toString() {
        return "UserDTO [name=" + name + ", age=" + age + ", city=" + city + ", grade=" + grade + "]";
    }
}

JacksonUtil.java

package com.bijian.test;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json字符与对像转换
 */
public final class JacksonUtil {

    public static ObjectMapper objectMapper;

    /**
     * 使用泛型方法,把json字符串转换为相应的JavaBean对象。
     * (1)转换为普通JavaBean:readValue(json,Student.class)
     * (2)转换为List,如List<Student>,将第二个参数传递为Student
     * [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
     * 
     * @param jsonStr
     * @param valueType
     * @return
     * @throws Exception 
     */
    public static <T> T readValue(String jsonStr, Class<T> valueType) throws Exception {
        
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }

        try {
            return objectMapper.readValue(jsonStr, valueType);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * json数组转List
     * @param jsonStr
     * @param valueTypeRef
     * @return
     * @throws Exception 
     */
    public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) throws Exception {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }

        try {
            return objectMapper.readValue(jsonStr, valueTypeRef);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 把JavaBean转换为json字符串
     * 
     * @param object
     * @return
     * @throws Exception 
     */
    public static String toJson(Object object) throws Exception {
        
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }

        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw e;
        }
    }
    
    public static void main(String[] args) throws Exception {
        
        //报Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "amount"异常
        String str = "{\"name\":\"白白\",\"age\":18,\"city\":\"shengzhen\",\"amount\":100,\"total\":\"172cm\"}";
        
        //OK
        //String str = "{\"name\":\"白白\",\"age\":18,\"city\":\"shengzhen\"}";
        UserDTO userDTO = JacksonUtil.readValue(str, UserDTO.class);
        System.out.println(userDTO);
    }
}

FastJsonUtil.java

package com.bijian.test;

import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;

public class FastJsonUtil {

    /**
     * 把json字符串转换为map
     * 
     * @param jsonStr
     * @return
     */
    public static Map<String, Object> json2Map(String jsonStr) {

        Map<String, Object> resMap = (Map<String, Object>) JSON.parse(jsonStr);
        return resMap;
    }
    
    /**
     * 把json字符串转换为相应的JavaBean对象
     * 
     * @param jsonStr
     * @param valueType
     * @return
     */
    public static <T> T toObject(String jsonStr, Class<T> valueType) {
        
        return JSON.parseObject(jsonStr, valueType);
    }
    
    /**
    * 把JavaBean转换为json字符串
    * 
    * @param object
    * @return
    * @throws Exception 
    */
    public static String toJson(Object object) {

        return JSON.toJSONString(object);
    }
    
    public static void main(String[] args) throws Exception {
        
        String str = "{\"name\":\"白白\",\"age\":18,\"city\":\"shengzhen\",\"amount\":100,\"total\":\"172cm\"}";
        UserDTO userDTO = FastJsonUtil.toObject(str, UserDTO.class);
        System.out.println(userDTO);
        
        
        Map<String, Object> resMap = FastJsonUtil.json2Map(str);
        for(Entry<String, Object> entry : resMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }
}