本文介绍了由于InvalidDefinitionException,Javamoney的CurrencyUnit不能用作字段的类并由Jackson进行反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pojo,它的javamoney库中的字段类型为 CurrencyUnit .当我编组这个pojo杰克逊时,他抛出了一个异常.当我没有定义任何默认构造函数时,我记得这个异常.但是在这种情况下,我不能维护 CurrencyUnit 类,因为它来自依赖项.我怎么还能做这项工作?

I have a pojo that has a field of type CurrencyUnit from the javamoney library. When I marshall this pojo Jackson throws an exception. 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. How can I still make this work?

例外:

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 包中的每种类型编写一个自定义序列化器/反序列化器,或者注册已创建的模块.例如: jackson-datatype-money .

You should write a custom serialiser/deserialiser for each type from javax.money package you want to use or register already created module. For example: jackson-datatype-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

这篇关于由于InvalidDefinitionException,Javamoney的CurrencyUnit不能用作字段的类并由Jackson进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:28