3

我有一个 pojo,它有一个CurrencyUnit来自 javamoney 库的类型字段。当我编组这个 pojo Jackson 时抛出异常。当我没有定义任何默认构造函数时,我记得这个异常。但在这种情况下,我无法维护CurrencyUnit该类,因为它来自依赖项。我怎样才能使这项工作?

例外:

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 
4

1 回答 1

4

javax.money您应该为要使用的包中的每种类型编写自定义序列化器/反序列化器或注册已创建的模块。例如:杰克逊数据类型钱

您需要添加依赖项:

<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
于 2019-11-05T18:26:46.433 回答