Spring boot Springboot将字符串转换为JavaMoney
我有一个客户端,它可以像这样发布到我的服务货币中:Spring boot Springboot将字符串转换为JavaMoney,spring-boot,java-money,Spring Boot,Java Money,我有一个客户端,它可以像这样发布到我的服务货币中: { "id": 1, "amount": "12.323,44" } 如何配置我的springboot在java货币字段中转换它? 这是我的目标 public class MyObject { private Long id; private Money amount; } 由于您要求使用spring boot,并且似乎是如何在MVC中映射时自动转换,因此您正在寻找与@ControllerAdvice相结合的@InitBinder
{
"id": 1,
"amount": "12.323,44"
}
如何配置我的springboot在java货币字段中转换它?
这是我的目标
public class MyObject {
private Long id;
private Money amount;
}
由于您要求使用spring boot,并且似乎是如何在MVC中映射时自动转换,因此您正在寻找与
@ControllerAdvice
相结合的@InitBinder
本S.O.文章中使用了一个示例
编写一个biding方法,将字符串转换为money或任何其他您想要的对象。使用jackson自定义反序列化程序
@JsonComponent
publi class MoneyJsonDeserializer
extends JsonDeserializer<Money> {
@Override
public Money deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
TextNode amountNode = (TextNode) treeNode.get(
"amount");
return new Money(amountNode.asText());
}
}
@JsonComponent
publi类MoneyJsonDeserializer
扩展JsonDeserializer{
@凌驾
公共资金反序列化(JsonParser JsonParser,
反序列化上下文(反序列化上下文)
抛出IOException、JsonProcessingException{
TreeNode TreeNode=jsonParser.getCodec().readTree(jsonParser);
TextNode amountNode=(TextNode)treeNode.get(
“金额”);
返回新货币(amountNode.asText());
}
}