在Java中通过Jackson将JSON long转换为日期

nbysray5  于 2022-11-08  发布在  Java
关注(0)|答案(3)|浏览(609)

我有一个JSON数据对象类,如下所示:

public class Plugins {

      private String id;
      private String name;

      @JsonProperty("created_at")
      private long createdAt; 
}

其中createdAt是创建日期的长时间戳。我使用这个类来备份一个JacksonObjectMapper对象,该对象解析来自外部API调用的JSON数据。我想知道是否可以让Jackson自动将created_at转换为可读的日期格式,并以StringDate的形式存储在Java中?

bxfogqkk

bxfogqkk1#

是否有可能让Jackson自动将created_at转换为可读日期格式,并以StringDate存储在Java中?
Date已过时,不建议使用。
自从Java 8(大约10年前发布)以来,我们有了现代的Time API,其中包括InstantLocalDateTimejava.time包中的其他类。
您可以更改POJO以使其正确存储日期-时间信息,而无需更改JSON有效负载。例如,created_at可以作为long值(如1665148545)接收,并转换为ZonedDateTime(或其他日期-时间表示形式,如IstantLocalDateTime)。

public class Plugins {
    private String id;
    private String name;
    private ZonedDateTime createdAt;

    public Plugins(@JsonProperty("id") String id,
                   @JsonProperty("name") String name,
                   @JsonProperty("created_at") long createdAt) {

        this.id = id;
        this.name = name;
        this.createdAt = Instant.ofEpochSecond(createdAt)
            .atZone(ZoneId.of("UTC"));
    }

    // getters, toString(), etc.
}
  • 用法示例:*
String json = """
    {
        "id": "1",
        "name": "someName",
        "created_at": 1665148545
    }""";

ObjectMapper mapper = new ObjectMapper();

System.out.println(mapper.readValue(json, Plugins.class));
  • 输出:*
lugins{id='1', name='someName', createdAt=2022-10-07T13:15:45}
bihw5rsg

bihw5rsg2#

您只需要注册JavaTimeModule模块,并使用Java-8时间包中的所需类型。请看下面的示例:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.Instant;

public class DateApp {
    private final static JsonMapper JSON_MAPPER = JsonMapper.builder()
            .enable(SerializationFeature.INDENT_OUTPUT)
            .addModule(new JavaTimeModule())
            .build();

    public static void main(String[] args) throws Exception {
        String json = "{\"id\": \"1\",\"name\":\"someName\",\"created_at\": 1665148545}";

        Plugins plugins = JSON_MAPPER.readValue(json, Plugins.class);
        System.out.println(plugins);
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Plugins {

    private String id;
    private String name;

    @JsonProperty("created_at")
    private Instant createdAt;
}

以上代码打印:

Plugins(id=1, name=someName, createdAt=2022-10-07T13:15:45Z)
h4cxqtbf

h4cxqtbf3#

在Jackson中使用自定义反序列化程序

您可以使用自订还原序列器,将日期从long转换为String或Date。此自订还原序列器会将json中的long值转换为定义的日期格式(Date或String)。

**请注意:**这里,我已经将epoch值转换为String数据类型。如果需要Date数据类型,您可以相应地更改CustomDateSerializer类的deserialize method的实现。

  • 您需要对需要自定义反序列化的字段使用下面的注解。*
    @JsonDeserialize(using = CustomDateSerializer.class)
    请在下面查找代码:
    插件.java
public class Plugins {

    private String id;
    private String name;
    @JsonDeserialize(using = CustomDateSerializer.class)
    @JsonProperty("created_at")
    private String createdAt;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    @Override
    public String toString() {
    return "Plugins{" +
            "id='" + id + '\'' +
            ", name='" + name + '\'' +
            ", createdAt='" + createdAt + '\'' +
            '}';
}
}

自定义日期序列化程序.java

public class CustomDateSerializer extends StdDeserializer<String> {

    public static String pattern = "dd MMM yyyy hh:mm:ss";

    public CustomDateSerializer() {
        this(StdDeserializer.class);
    }

    protected CustomDateSerializer(Class<?> c) {
        super(c);
    }

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(new Date(jsonParser.getLongValue()));//change the implementation of deserialise method if date format is needed.
    }

}

测试.java

public class Test {
    public static void main(String[] args) throws JsonProcessingException {
     //For sample input json, here i have used Text Blocks feature available from JDK 15 to have the string in readable format.
        String json = """
                {
                "id":"1",
                "name":"test",
                "created_at":1665158083000
                }
                """;
        ObjectMapper mapper = new ObjectMapper();
        Plugins test = mapper.readValue(json,Plugins.class);
        System.out.println(test);
    }
}

输出:

Plugins{id='1', name='test', createdAt='07 Oct 2022 09:24:43'}

相关问题