Redis参数转换API

编辑工具API

此工具API主要负责将用户参数转换为JSON或者将JSOn串转换为对象,简化客户端的使用

1.创建工具类ObjectMapperUtil

public class ObjectMapperUtil {}

2.创建工具API对象

    private static final ObjectMapper MAPPER = new ObjectMapper();

3.封装API 将传入对象转换为JSON

//2.封装API 将对象转化为JSON
    public static String toJSON(Object object){

        if(object == null){
            throw new RuntimeException("传入对象不能为null");
        }

        try {
            String json = MAPPER.writeValueAsString(object);
            return json;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

4.3.将JSON串转化为对象 用户传递什么类型,则返回什么对象

返回值类型是由调用者设定所以设置为 T

 public static <T> T toObject(String json,Class<T> target){

        //1.校验参数是否有效
        if(json == null || "".equals(json) || target == null){
            //参数有误.
            throw new RuntimeException("参数不能为null");
        }

        //2.执行业务处理
        try {
            T t = MAPPER.readValue(json, target);
            return t;
        } catch (JsonProcessingException e) {
            //将报错信息通知其他人
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

5.测试

//工具API测试
    @Test
    public void test02(){
        ItemDesc itemDesc = new ItemDesc();
        itemDesc.setItemId(100L).setItemDesc("测试JSON转化").setCreated(new Date())
                .setUpdated(itemDesc.getCreated());
        String json = ObjectMapperUtil.toJSON(itemDesc);
        ItemDesc itemDesc2 = ObjectMapperUtil.toObject(json, ItemDesc.class);
        System.out.println(itemDesc2);
    }

猜你喜欢

转载自blog.csdn.net/weixin_47409774/article/details/107968039
今日推荐