Spring Boot 将时间戳格式的JSON Date反序列化为具有LocalDatetime的Java Object

cl25kdpy  于 2023-04-30  发布在  Spring
关注(0)|答案(1)|浏览(144)

项目详情:Sping Boot with Gradle
我的java类:

public class Sale{
   private String storeNumber;
   @JsonFormat(pattern  = "yyyy-MM-dd'T'HH:mm:ss")
   private LocalDateTime saleDateTime;
   // getter, setter
}

这个对象被序列化为JSON,看起来像这样:

{
   "storeNumber": "023",
   "saleDateTime": {
     "date": {
      "year" : 2023,
      "month" : 4,
      "day" : 4
     },
     "time": {
      "hour" : 16,
      "minute" : 28,
      "second" : 45,
      "nano" : 0
     }
  }
}

我想使用JacksonObjectMapper将这个JSON转换回销售对象。readValue(json,销售.你将如何从显示的格式反序列化它?因为这就是我从我的数据库里得到的。我希望能够为这种格式的日期数据编写一个自定义的反序列化器,因为我们有很多类似的生产数据。我将不得不找到一种方法来反序列化给定日期的对象。
到目前为止我所尝试的:

  • 添加jackson-datatype-jr 310的gradle依赖
  • 将JavaTimeModule注册为Map器。public void run();
  • 做了一个自定义的反序列化器,扩展了JsonDeserializer并覆盖了public LocalDateTime反序列化(JsonParser p,DeserializationContext context),并将其注册到ObjectMapper作为Map器。registerModule(LocalDateTime.类,new CustomDeserializer())

但没有用。我得到Jackon MismatchedInputException:无法反序列化类型“java”的值。从Object值(token 'JsonToken.START_OBJECT')

sdnqo3pr

sdnqo3pr1#

以下作品。基本上这是你的第三个选择-不知道你错过了什么。

import java.io.IOException;
import java.time.LocalDateTime;

import com.example.demo.model.Sale;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.IntNode;

public class CustomLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> { 
public CustomLocalDateTimeDeserializer() { 
    this(null); 
} 

public CustomLocalDateTimeDeserializer(Class<?> vc) { 
    super(vc); 
}

@Override
public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) 
  throws IOException, JsonProcessingException {
    JsonNode node = jp.getCodec().readTree(jp);
    
    JsonNode date = node.get("date");
    int year = (Integer) ((IntNode) date.get("year")).numberValue();
    int month = (Integer) ((IntNode) date.get("month")).numberValue();
    int dayOfMonth = (Integer) ((IntNode) date.get("day")).numberValue();
    
    
    JsonNode time = node.get("time");
    int hour = (Integer) ((IntNode) time.get("hour")).numberValue();
    int minute = (Integer) ((IntNode) time.get("minute")).numberValue();
    int second = (Integer) ((IntNode) time.get("second")).numberValue();
    int nanoOfSecond = (Integer) ((IntNode) time.get("nano")).numberValue();
    
    return LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond);
}

public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
    mapper.registerModule(module);
    
    
    String json = "{\r\n" + 
            "   \"storeNumber\": \"023\",\r\n" + 
            "   \"saleDateTime\": {\r\n" + 
            "     \"date\": {\r\n" + 
            "      \"year\" : 2023,\r\n" + 
            "      \"month\" : 4,\r\n" + 
            "      \"day\" : 4\r\n" + 
            "     },\r\n" + 
            "     \"time\": {\r\n" + 
            "      \"hour\" : 16,\r\n" + 
            "      \"minute\" : 28,\r\n" + 
            "      \"second\" : 45,\r\n" + 
            "      \"nano\" : 0\r\n" + 
            "     }\r\n" + 
            "  }\r\n" + 
            "}";
    

    Sale readValue = mapper.readValue(json, Sale.class);
    
    System.out.println(readValue);
}

}

输出如下:

Sale(storeNumber=023, saleDateTime=2023-04-04T16:28:45)

依赖关系-没有什么特别的

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.5</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

相关问题