JsonUtils的实现:对象与json相互转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bigtree_3721/article/details/82870546

pom.xml依赖

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.1</version>
</dependency> 

JsonUtils.java 内容:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by Bill.Tang on 2018-9-27.
 */

public class JsonUtils {
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     */
    public static String objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
 /**
     * 将json结果集转化为对象
     */
    public static <T> T jsonToPoJo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
             e.printStackTrace();
        }
        return null;
    }
    /**
     * 将json数据转换成pojo对象list
     */
    public  static <T> T jsonToList(String jsonData,TypeReference<T> typeReference) {
        try {
            return MAPPER.readValue(jsonData, typeReference);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

使用例子代码

List<DeviceIdBeanRes> deviceIdBeanResList = 
JsonUtils.parseJson("your json", new TypeReference<List<yourclass>>() {
        });

猜你喜欢

转载自blog.csdn.net/bigtree_3721/article/details/82870546