在日常的项目开发中,接口与接口之间、前后端之间的数据传输一般都是使用JSON格式,那必然会封装一些常用的Json数据转化的工具类,本文讲解下如何利用Jackson封装高复用性的Json转换工具类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com...common.util.StringUtil; /** * jsonUtil工具类 * * @author ryz * @since 2020-05-11 */ public class JsonUtil { private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class); private static ObjectMapper mapper = new ObjectMapper(); /** * 对象转Json格式字符串 * @param obj 对象 * @return Json格式字符串 */ public static <T> String obj2String(T obj) { if (obj == null) { return null; } try { return obj instanceof String ? (String) obj : mapper.writeValueAsString(obj); } catch (JsonProcessingException e) { LOGGER.warn("Parse Object to String error : {}", e.getMessage()); return null; } } /** * 对象转Json格式字符串(格式化的Json字符串) * @param obj 对象 * @return 美化的Json格式字符串 */ public static <T> String obj2StringPretty(T obj) { if (obj == null) { return null; } try { return obj instanceof String ? (String) obj : mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (JsonProcessingException e) { LOGGER.warn("Parse Object to String error : {}", e.getMessage()); return null; } } /** * 字符串转换为自定义对象 * @param str 要转换的字符串 * @param clazz 自定义对象的class对象 * @return 自定义对象 */ public static <T> T jsonToObj(String str, Class<T> clazz){ if(StringUtil.isEmpty(str) || clazz == null){ return null; } try { return clazz.equals(String.class) ? (T) str : mapper.readValue(str, clazz); } catch (Exception e) { LOGGER.warn("Parse String to Object error : {}", e.getMessage()); return null; } } /** * 集合对象与Json字符串之间的转换 * @param str 要转换的字符串 * @param typeReference 集合类型如List<Object> * @param <T> * @return */ public static <T> T jsonToObj(String str, TypeReference<T> typeReference) { if (StringUtil.isEmpty(str) || typeReference == null) { return null; } try { return (T) (typeReference.getType().equals(String.class) ? str : mapper.readValue(str, typeReference)); } catch (IOException e) { LOGGER.warn("Parse String to Object error", e); return null; } } /** * 集合对象与Json字符串之间的转换 * @param str 要转换的字符串 * @param collectionClazz 集合类型 * @param elementClazzes 自定义对象的class对象 * @param <T> * @return */ public static <T> T string2Obj(String str, Class<?> collectionClazz, Class<?>... elementClazzes) { JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes); try { return mapper.readValue(str, javaType); } catch (IOException e) { LOGGER.warn("Parse String to Object error : {}" + e.getMessage()); return null; } } } |
User对象类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | package com...utils; /** * 功能描述 * * @since 2020-05-11 */ public class User { private Integer id; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | /* * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. */ package ....utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; public class JsonUtilTest { private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtilTest.class); public static void main(String[] args) { User user1 = new User(); user1.setId(1); user1.setEmail("[email protected]"); String userJsonstr = JsonUtil.obj2String(user1); String userJsonPretty = JsonUtil.obj2StringPretty(user1); LOGGER.info("userJson: {}", userJsonPretty); User user2 = JsonUtil.string2Obj(userJsonstr, User.class); user2.setId(2); user2.setEmail("[email protected]"); List<User> userList = new ArrayList<>(); userList.add(user1); userList.add(user2); String userListJson = JsonUtil.obj2String(userList); List<User> userListBean = JsonUtil.string2Obj(userListJson, new TypeReference<List<User>>() {}); if (userListBean != null) { userListBean.forEach(user -> { System.out.println(user.getId() + " : " + user.getEmail()); }); } List<User> userListBean2 = JsonUtil.string2Obj(userListJson, List.class, User.class); if (userListBean2 != null) { userListBean2.forEach(user -> { System.out.println(user.getId() + " : " + user.getEmail()); }); } } } |
运行结果
