[英]CurrencyUnit of javamoney can't be used as class of a field and deserialized by Jackson due InvalidDefinitionException
I have a pojo that has a field of type CurrencyUnit
from the javamoney library.我有一个 pojo,它有一个来自 javamoney 库的
CurrencyUnit
类型的字段。 When I marshall this pojo Jackson throws an exception.当我编组这个 pojo Jackson 时抛出异常。 I remember this exception when I did not define any default constructor.
当我没有定义任何默认构造函数时,我记得这个异常。 But in this case I can not maintain the
CurrencyUnit
class since it's coming from a dependency.但在这种情况下,我无法维护
CurrencyUnit
class,因为它来自依赖项。 How can I still make this work?我怎样才能使这项工作?
Exception:例外:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `javax.money.CurrencyUnit` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information\n at
You should write a custom serialiser/deserialiser for each type from javax.money
package you want to use or register already created module.您应该为
javax.money
package 中的每种类型编写自定义序列化器/反序列化器,以使用或注册已创建的模块。 For example: jackson-datatype-money .例如:杰克逊数据类型钱。
You need to add dependency :您需要添加依赖项:
<dependency>
<groupId>org.zalando</groupId>
<artifactId>jackson-datatype-money</artifactId>
<version>1.1.1</version>
</dependency>
Simple example how to use:简单示例如何使用:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.zalando.jackson.datatype.money.MoneyModule;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
public class JsonMoneyApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.registerModule(new MoneyModule());
CurrencyUnit cu = Monetary.getCurrency("USD");
String json = mapper.writeValueAsString(cu);
System.out.println(json);
CurrencyUnit unit = mapper.readValue(json, CurrencyUnit.class);
System.out.println(unit);
}
}
above code prints:上面的代码打印:
"USD"
USD
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.