gpt4 book ai didi

java - jackson 使一个java属性的两个json属性

转载 作者:行者123 更新时间:2023-11-29 08:34:35 25 4
gpt4 key购买 nike

我在 rest api 中使用 jackson 时遇到了一些不便的问题。我正在使用 jackson 序列化在 java.time 中具有任何类型属性的对象,例如:

public class DomainObject{
public LocalDateTime start;
}

我可以使用 jackson 来产生这样的东西:

{
start: '2017-12-31 17:35:22'
}

我可以用它来产生这样的东西:

{
start: 102394580192345 //milliseconds
}

但我想要两者兼有,在 JS 中使用的毫秒数和字符串表示形式,供用户使用纯粹没有 js 前端的 rest-api。 (主要是我,用于调试)

那么有什么办法可以让jackson产生以下结果吗?

{
start: 102394580192345 //milliseconds
startString: '2017-12-31 17:35:22'
}

最佳答案

您可以编写一个自定义的 Jackson Serializer,然后必须在应用程序中注册它。之后,该数据类型的每次出现都将以这种方式序列化。即使要序列化的数据类型在另一个数据类型中。 (就像你的例子一样)

注意:请原谅我不要为 LocalDateTime 编写它,因为我在我的应用程序中为 ZonedDateTime 编写了它。根据您的需要重写它应该不是一项艰巨的任务。

public class ZonedDateTimeSerializer extends JsonSerializer<ZonedDateTime>
{

@Override
public void serialize( ZonedDateTime value, JsonGenerator gen, SerializerProvider serializers ) throws IOException
{
gen.writeStartObject();
gen.writeFieldName( "timestamp" );
gen.writeString( Long.toString( value.toInstant().toEpochMilli() ) );
gen.writeFieldName( "offset" );
gen.writeString( value.getOffset().toString() );
gen.writeFieldName( "zone" );
gen.writeString( value.getZone().toString() );
gen.writeFieldName( "ts" );
gen.writeString( StringUtils.convertZonedDateTimeToISO8601String( value ) );
gen.writeEndObject();
}

}

然后像这样为 Jackson 的 ObjectMapper 注册:

    objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule( "MyModule" );
module.addSerializer( ZonedDateTime.class, new ZonedDateTimeSerializer() );
objectMapper.registerModule( module );

在此过程中,我建议创建一个 Producer ( CDI ),它将始终返回一个默认添加此序列化程序的 objectMapper。但我会把这个任务留给你去研究;)

关于java - jackson 使一个java属性的两个json属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45188734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com