在通过自定义转换器

时间:2017-05-18 19:37:59

标签: java spring amazon-web-services amazon-dynamodb objectmapper

我想在Dynamo中存储一个项目:

public class Statement {
@DynamoDBTypeConverted(converter = ListLineItemConverter.class)
private List<LineItem> items;
}

,LineItem的定义如下:

public class LineItem {
private ZonedDateTime dateStart;
private ZonedDateTime dateEnd;
private long balance;

@DynamoDBTypeConverted(converter = ZonedDateTimeConverter.class)
public getDateStart() {...}

@DynamoDBTypeConverted(converter = ZonedDateTimeConverter.class)
public getDateEnd() {...} 
}

我一直在使用ZonedDateTime的已知工作转换器,如下所示:

public class ZonedDateTimeConverter implements DynamoDBTypeConverter<String, ZonedDateTime> {
    public ZonedDateTimeConverter(){}

    @Override
    public String convert(final ZonedDateTime time) {
        return time.toString();
    }

    @Override
    public ZonedDateTime unconvert(final String stringValue) {
        return ZonedDateTime.parse(stringValue);
    }
}

当转换器在基类上注释时,转换器工作正常。但我有一个嵌套在项目列表中的自定义类型,我似乎无法弄清楚如何让DynamoDB正确转换/转换嵌套的ZonedDateTime。

我甚至为ListItem写了一个自定义转换器而没有运气:

public class ListLineItemConverter implements DynamoDBTypeConverter<String, List<LineItem>> {

    private ObjectMapper objectMapper;

    public ListLineItemConverter() {
        objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // THIS LINE OF CODE FIXED THE ISSUE FOR ME
        objectMapper.findAndRegisterModules();
        // THIS LINE OF CODE FIXED THE ISSUE FOR ME
    }

    @Override
    public String convert(List<LineItem> object) {
        try {
            String result = objectMapper.writeValueAsString(object);
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("bad json marshalling");
        }
    }

    @Override
    public List<LineItem> unconvert(String object) {
        try {
            return objectMapper.readValue(object, new TypeReference<List<LineItem>>() {});
        } catch (IOException e) {
            throw new RuntimeException("bad json unmarshalling");
        }
    }
}

我似乎没有使用注释的组合来实现这一点。我总是得到:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.time.ZonedDateTime: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)

编辑:如果我从ZonedDateTime注释掉LineItem的实例,那么代码就可以正常运行了。因此,DynamoDB在隐藏3级深度时读取@DynamoDBTypeConverted注释时遇到问题:

Statement.items.get[0].dateStart // annotations aren't working at this level

Statement.items.get[0].dateEnd // annotations aren't working at this level

1 个答案:

答案 0 :(得分:1)

在ZonedDateTime的嵌套实例上使用Jackson解析器时看起来有问题,并且它不会自动拾取它。

我已经切换到更新版本的Jackson,甚至包括JSR310模块,以确保支持编组/解组新的java 8时间结构,但是唉。

奇怪的是,有一行代码为我修复了它:

objectMapper.findAndRegisterModules();

取自:https://stackoverflow.com/a/37499348/584947