Article Directory
- Article Table of Contents
- Text
- 1. Use the tool package (for example: hutool)
- 2. Write Json tool class
Text
In the process of web development, we often encounter scenarios that require JSON data, so we need some tools to help us quickly convert objects into JSON data and deserialize JSON data into Java objects.
1. Using tool kits (for example: hutool)
Introduce dependencies:
<!-- hutool --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.22</version> </dependency>
Instructions:
@Test void testJson() { UserEntity user = new UserEntity(); // Convert json string String json = JSONUtil.toJsonStr(user); System.out.println(json); //Convert to entity class object UserEntity bean = JSONUtil.toBean(json, UserEntity.class); System.out.println(bean); }
Although this method is simple, in actual development, we may not be allowed to use third-party toolkits for development. How to solve? Of course, we need to write a tool class ourselves to implement this function.
2. Writing Json tool class
The jackson serialization tool is used here (determined based on project requirements)
Introduce dependencies:
<!-- jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency>
Tool class writing:
//package.. import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class JsonUtils { private static ObjectMapper objectMapper = new ObjectMapper(); static { //Set visibility objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // ignore case objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); // Failed when canceling a field that does not exist objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Enable hump conversion objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); // Serialize date as readable string instead of timestamp objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); //Set the time module (format, if not set, the default format will be output) JavaTimeModule timeModule = new JavaTimeModule(); // LocalDateTime timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai")))); timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai")))); // LocalDate timeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.of("Asia/Shanghai")))); timeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.of("Asia/Shanghai")))); //Set a custom time module objectMapper.registerModule(timeModule); } /** * Serialize the object into a JSON string * * @param object object * @return json string */ public static String toJson(Object object) { try { if (object == null) { return null; } return objectMapper.writeValueAsString(object); } catch (Exception e) { return null; } } /** * Deserialize JSON string into object * * @param json json string * @param valueType object type * @param <T> t * @return t */ public static <T> T toBean(String json, Class<T> valueType) { try { if (json == null || json.isEmpty()) { return null; } return objectMapper.readValue(json, valueType); } catch (Exception e) { return null; } } /** * Get the Integer value * * @param json json string * @param fieldName field name * @return integer||null */ public static Integer getIntValue(String json, String fieldName) { try { if (json == null || json.isEmpty()) { return null; } if (fieldName == null || fieldName.isEmpty()) { return null; } JsonNode jsonNode = objectMapper.readTree(json); if (jsonNode == null) { return null; } return jsonNode.get(fieldName) .asInt(); } catch (Exception e) { return null; } } /** * Get the String value * * @param json json string * @param fieldName field name * @return string||null */ public static String getStrValue(String json, String fieldName) { try { if (json == null || json.isEmpty()) { return null; } if (fieldName == null || fieldName.isEmpty()) { return null; } JsonNode jsonNode = objectMapper.readTree(json); if (jsonNode == null) { return null; } return jsonNode.get(fieldName) .asText(); } catch (Exception e) { return null; } } /** * Convert json string to JsonNode * * @param json json string * @return JsonNode object || null */ public static JsonNode getJsonNode(String json) { try { return objectMapper.readTree(json); } catch (JsonProcessingException e) { return null; } } }