适当的方法将objectid映射到弹簧中的dto中串起
我正在与Spring Websocket合作。 当我将此DTO发送为响应时,我有Message
的DTO
@AllArgsConstructor
@Data
public class MessageDto {
private ObjectId messageId;
private ObjectId chatId;
}
,objectId
tto Maps中的字段如下:
我如何映射<代码> objectid 字段<代码>字符串喜欢62790C02513AD11442EEC6D7
?
I am working with Spring WebSocket. I have this DTO of the Message
@AllArgsConstructor
@Data
public class MessageDto {
private ObjectId messageId;
private ObjectId chatId;
}
When I send this DTO as response, ObjectId
fields in DTO maps like this:
How can I map ObjectId
field into String
like 62790c02513ad11442eec6d7
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Spring使用
Jackson
将对象映射到JSON
,因此映射ObjectID
字段的正确方法是配置Jackson 连续化器。
创建一个序列化器类:
然后在DTO类中指定序列化器:
总而言之,
ObjectId
messagedto
对象的字段将像json中的字符串一样序列化。
当然,对于对象的 json ,存在一个问题。有
jsondeserializer&lt;
和@jsondeserialize
来解决此问题。但是(映射objectId
类字段)deserializer是没有用的,因为ObjectId
已经具有一个构造函数,它接收string
参数,所以杰克逊
将使用它。Spring uses
Jackson
to map objects toJSON
, so the proper way to mapObjectId
field in a object is to configureJackson
serializers.Create a serializer class:
And then specify the serializer in a DTO class:
In conclusion, the
ObjectId
field of theMessageDto
object will be serialized like a string inJSON
Of course, there is a problem to deserialize
JSON
to an object. There areJsonDeserializer<>
and@JsonDeserialize
to solve this problem. But there (mappingObjectId
class field) deserializer is useless, becauseObjectId
already have a constructor, that receives aString
parameter, soJackson
will use it.