我正在使用spring boot来创建一个api,从mongodb中检索值。我面临的问题是Decimal128
字段被序列化为:
"userid": {
"high": 3476778912330022912,
"low": 10776,
"naN": false,
"infinite": false,
"finite": true,
"negative": false
}
这是我的控制器的主体:
var wrappers = new EmbeddedWrappers(false);
var collection = mongoTemplate.getCollection("blah");
var result = collection.find().limit(1000).into(new ArrayList<>());
if (result == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(new Resources<>(Arrays.asList(wrappers.wrap(result))));
有什么想法可以正确地序列化
Decimal128
值,以便仅具有值本身吗? 最佳答案
根据评论:
@Configuration
public class ObjectMapperConfig {
@Bean
public ObjectMapper objectMapper() {
var mapper = new ObjectMapper();
var module = new SimpleModule();
module.addSerializer(Decimal128.class, new Decimal128Serializer());
mapper.registerModule(module);
return mapper;
}
private static class Decimal128Serializer extends JsonSerializer<Decimal128> {
@Override
public void serialize(Decimal128 v, JsonGenerator g, SerializerProvider p) throws IOException {
g.writeNumber(v.bigDecimalValue());
}
}
}