javamoney 的 CurrencyUnit 不能用作字段的 class 并且由于 InvalidDefinitionException 而被 Jackson 反序列化
CurrencyUnit of javamoney can't be used as class of a field and deserialized by Jackson due InvalidDefinitionException
我有一个 pojo,它有一个来自 javamoney 库的 CurrencyUnit
类型的字段。当我整理这个 pojo 时,Jackson 抛出异常。当我没有定义任何默认构造函数时,我记得这个异常。但是在这种情况下,我无法维护 CurrencyUnit
class 因为它来自依赖项。我怎样才能让它继续工作?
异常:
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
您应该为要使用的 javax.money
包中的每种类型编写自定义 serialiser/deserialiser 或注册已创建的模块。例如:jackson-datatype-money.
您需要添加dependency:
<dependency>
<groupId>org.zalando</groupId>
<artifactId>jackson-datatype-money</artifactId>
<version>1.1.1</version>
</dependency>
简单的使用方法示例:
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);
}
}
以上代码打印:
"USD"
USD
我有一个 pojo,它有一个来自 javamoney 库的 CurrencyUnit
类型的字段。当我整理这个 pojo 时,Jackson 抛出异常。当我没有定义任何默认构造函数时,我记得这个异常。但是在这种情况下,我无法维护 CurrencyUnit
class 因为它来自依赖项。我怎样才能让它继续工作?
异常:
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
您应该为要使用的 javax.money
包中的每种类型编写自定义 serialiser/deserialiser 或注册已创建的模块。例如:jackson-datatype-money.
您需要添加dependency:
<dependency>
<groupId>org.zalando</groupId>
<artifactId>jackson-datatype-money</artifactId>
<version>1.1.1</version>
</dependency>
简单的使用方法示例:
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);
}
}
以上代码打印:
"USD"
USD