基于Jackson的工具类

package com.example.base.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author Other
 */
public class JacksonUtil {

    private static final Logger logger = LoggerFactory.getLogger(JacksonUtil.class);

    private final static ObjectMapper MAPPER;

    static {
        MAPPER = new ObjectMapper();
        // 忽略Json中在对象不存在对应属性
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 忽略空Bean转Json错误
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 设置属性为 空("") 或者为 NULL 都不序列化,默认 JsonInclude.Include.ALWAYS
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss
        // MAPPER.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
    }

    /**
     * Object TO Json String 字符串输出(推荐)
     */
    public static String toJson(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            logger.error("method=toJSON() is convert error, errorMsg:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * Object TO Json String 字符串输出(输出空字符)
     */
    public static String toJsonEmpty(Object object) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
                @Override
                public void serialize(Object param, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                    //设置返回null转为 空字符串""
                    jsonGenerator.writeString("");
                }
            });
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            logger.error("method=toJsonEmpty() is convert error, errorMsg:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * Json 转为 Jave Bean
     */
    public static <T> T toBean(String text, Class<T> clazz) {
        try {
            return MAPPER.readValue(text, clazz);
        } catch (Exception e) {
            logger.error("method=toBean() is convert error, errorMsg:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * Json 转为 Map
     */
    public static <K, V> Map<K, V> toMap(String text) {
        try {
            return toObject(text, new TypeReference<Map<K, V>>() {
            });
        } catch (Exception e) {
            logger.error("method=toMap() is convert error, errorMsg:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * Json 转 List, Class 集合中泛型的类型,非集合本身
     */
    public static <T> List<T> toList(String text) {
        try {
            return toObject(text, new TypeReference<List<T>>() {
            });
        } catch (Exception e) {
            logger.error("method=toList() is convert error, errorMsg:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * Json 转 Object
     */
    public static <T> T toObject(String text, TypeReference<T> typeReference) {
        try {
            if (!typeReference.getType().equals(String.class)) {
                throw new ClassCastException("转换失败,Json对象类型不匹配");
            }
            return verifyParams(text) ? MAPPER.readValue(text, typeReference) : null;
        } catch (Exception e) {
            logger.error("method=toObject() is convert error, errorMsg:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 参数校验
     */
    private static boolean verifyParams(Object object) {
        if (null != object) {
            if (object instanceof String) {
                return !"".equals(object);
            }
        }
        return false;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Jackson 工具类是一种用于将 JSON 数据序列化和反序列化为 Java 对象的工具类。该工具类是基于 Jackson 库开发的,可以在 Spring 应用程序中很方便地使用。 在 Spring 应用程序中使用 Spring Jackson 工具类,步骤如下: 1. 添加依赖:在 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.3</version> </dependency> ``` 2. 创建配置类:创建一个配置类,用于配置 Jackson 的 ObjectMapper 对象。可以在配置类中添加自定义的序列化和反序列化器。 ``` @Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return objectMapper; } } ``` 3. 使用工具类:在需要序列化或反序列化 JSON 数据的地方使用 Spring Jackson 工具类。 ``` @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } @PostMapping("/users") public User addUser(@RequestBody User user) { return userService.addUser(user); } } ``` 在上面的例子中,使用了 @RequestBody 注解将 JSON 数据反序列化为 User 对象,在返回值中使用了 Spring Jackson 工具类将 User 对象序列化为 JSON 数据返回给客户端。 总之,Spring Jackson 工具类是一种方便易用的 JSON 序列化和反序列化工具类,对于需要对 JSON 数据和 Java 对象进行转换的 Spring 应用程序来说非常实用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值