java - 亚马逊云数据库 : Could not unconvert attribute error

标签 java json amazon-web-services amazon-dynamodb objectmapper

我有一个问题,我无法处理。例如,我在 KitchenService 中创建了 CRUD 方法。我有 addProduct 等方法,这些方法工作正常。但是我有 Recipe 类,我在其中使用 Product 类字段。在这种情况下,我遇到了很大的问题。

我的 addRecipe 方法:

public Recipe addRecipe (Recipe recipe){

    List<RecipeElement> recipeElements = recipe.getRecipeElements();
    for (RecipeElement recipeElement : recipeElements) {
        String id = recipeElement.getProduct().getId();
        Product product = databaseController.get(Product.class, id);
        recipeElement.setProduct(product);
    }

    databaseController.saveRecipe(recipe);
    logger.log("Recipe created");

    return recipe;

构建成功所以我想在 POSTMAN 中测试它,这就是我发送的 JSON 女巫的样子:

{"id":null,"name":"test3","labels":["GLUTEN_FREE"],"author":{"name":"Plejer Annołn","id":"testID2"},"media":{"name":"heheszki","url":"http://blabla.pl","mediaType":"IMAGE"},"recipeElements":[{"product":{"id":"ecacaf36-29a2-41c6-942e-be5a715ed094"},"weight":"100"}],"approved":false}

然后我收到“消息”:“内部服务器错误”,所以我正在检查日志,这就是我在那里发现的:

Product[Media]; could not unconvert attribute: com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException

Caused by: com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: could not invoke public void pl.javamill.model.kitchen.Product.setMedia(pl.javamill.model.common.Media) on class pl.kitchen.Product with value {name=heheszki, url=http://blabla.pl, mediaType=IMAGE} of type class java.util.LinkedHashMap

配方类是这样的:

@DynamoDBTable(tableName = "recipe")
public class Recipe extends Request {
/**
 * Id of kitchen content
 */
private String id;
/**
 * Name of recipe
 */
private String name;

/**
 * Labels of product for example gluten fee product
 */
private List<KitchenLabel> labels;

/**
 * Author of content.
 */
private Author author;

/**
 * Address of content image.
 */
private Media media;

private Boolean approved;

private List<RecipeElement> recipeElements;

@DynamoDBHashKey(attributeName = "id")
@DynamoDBAutoGeneratedKey
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@DynamoDBAttribute(attributeName = "Name")
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@DynamoDBTypeConverted(converter = EnumConverter.class)
@DynamoDBAttribute(attributeName = "Labels")
public List<KitchenLabel> getLabels() {
    return labels;
}

public void setLabels(List<KitchenLabel> labels) {
    this.labels = labels;
}

@DynamoDBTypeConverted(converter = ObjectConverter.class)
@DynamoDBAttribute(attributeName = "Author")
public Author getAuthor() {
    return author;
}

public void setAuthor(Author author) {
    this.author = author;
}

@DynamoDBTypeConverted(converter = ObjectConverter.class)
@DynamoDBAttribute(attributeName = "Media")
public Media getMedia() {
    return media;
}

public void setMedia(Media media) {
    this.media = media;
}

@DynamoDBAttribute(attributeName = "Approved")
public Boolean getApproved() {
    return approved;
}

public void setApproved(Boolean approved) {
    this.approved = approved;
}

@DynamoDBTypeConverted(converter = ObjectConverter.class)
@DynamoDBAttribute(attributeName = "RecipeElements")
public List<RecipeElement> getRecipeElements() {
    return recipeElements;
}

public void setRecipeElements(List<RecipeElement> recipeElements) {
    this.recipeElements = recipeElements;
}

食谱元素类:

public class RecipeElement {


private Product product;
private Integer weight;

@DynamoDBTypeConverted(converter = ObjectConverter.class)
@DynamoDBHashKey(attributeName = "product")
public Product getProduct() {
    return product;
}

public void setProduct(Product product) {
        this.product = product;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }
}

和产品类别:

@DynamoDBTable(tableName = "product")
public class Product extends Request {
    /**
     * Id of kitchen content
     */
    private String id;

    /**
     * Name of product
     */
    private String name;

    /**
     * Calories in 100g
     */
    private Integer calories;

    /**
     * Fat in 100g
     */
    private Double fat;

    /**
     * Total carbo in 100g
     */
    private Double carbo;

    /**
     * Total Protein in 100g
     */
    private Double protein;

    /**
     * Labels of product for example gluten fee product
     */
    private List<ProductKind> productKinds;

    /**
     * Author of content.
     */
    private Author author;

    /**
     * Address of content image.
     */
    private Media media;

    private Boolean approved;

    @DynamoDBHashKey(attributeName = "id")
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @DynamoDBAttribute(attributeName = "Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @DynamoDBAttribute(attributeName = "Calories")
    public Integer getCalories() {
        return calories;
    }

    public void setCalories(Integer calories) {
        this.calories = calories;
    }

    @DynamoDBAttribute(attributeName = "Fat")
    public Double getFat() {
        return fat;
    }

    public void setFat(Double fat) {
        this.fat = fat;
    }

    @DynamoDBAttribute(attributeName = "Carbo")
    public Double getCarbo() {
        return carbo;
    }

    public void setCarbo(Double carbo) {
        this.carbo = carbo;
    }

    @DynamoDBAttribute(attributeName = "Protein")
    public Double getProtein() {
        return protein;
    }

    public void setProtein(Double protein) {
        this.protein = protein;
    }

    @DynamoDBTypeConverted(converter = EnumConverter.class)
    @DynamoDBAttribute(attributeName = "ProductKinds")
    public List<ProductKind> getProductKinds() {
        return productKinds;
    }

    public void setProductKinds(List<ProductKind> productKinds) {
        this.productKinds = productKinds;
    }

    @DynamoDBTypeConverted(converter = ObjectConverter.class)
    @DynamoDBAttribute(attributeName = "Author")
    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    @DynamoDBTypeConverted(converter = ObjectConverter.class)
    @DynamoDBAttribute(attributeName = "Media")
    public Media getMedia() {
        return media;
    }

    public void setMedia(Media media) {
        this.media = media;
    }

    @DynamoDBAttribute(attributeName = "Approved")
    public Boolean getApproved() {
        return approved;
    }

    public void setApproved(Boolean approved) {
        this.approved = approved;
    }

这是我的转换器类:

public class ObjectConverter<T extends Object> 
implements DynamoDBTypeConverter<String, T> {

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convert(T object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new IllegalArgumentException("Unable to parse JSON");
    }

    @Override
    public T unconvert(String object) {
        try {
            T unconvertedObject = objectMapper.readValue(object, 
                new TypeReference<T>() {
            });
            return unconvertedObject;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

有人可以帮我解决这个问题吗?

最佳答案

简答:

Media 类添加一个公共(public)的空构造函数。

长答案:

在您的代码中,当您执行 databaseController.get(Product.class, id) 时,您正在调用下划线方法 public T unconvert(final Map<String,AttributeValue> object)DynamoDBMapperTableModel :

@Override
public T unconvert(final Map<String,AttributeValue> object) {
    final T result = StandardBeanProperties.DeclaringReflect.<T>newInstance(targetType);
    if (!object.isEmpty()) {
        for (final DynamoDBMapperFieldModel<T,Object> field : fields()) {
            try {
                final AttributeValue value = object.get(field.name());
                if (value != null) {
                    field.unconvertAndSet(result, value);
                }
            } catch (final RuntimeException e) {
                throw new DynamoDBMappingException(
                    targetType.getSimpleName() + "[" + field.name() + "]; could not unconvert attribute", e
                );
            }
        }
    }
    return result;
}

在此方法的第一行中,使用反射创建了表模型的新实例(在您的例子中是 Product 的新实例),然后新实例的字段被转换为所需的类,并且相应地设置。

StandardBeanProperties.DeclaringReflect.<T>newInstance(targetType)调用 .newInstance()targetType , 它的类型是 Class<T> .

写在Class.newInstance() documentation , InstantiationException如果该类没有 nullary 构造函数,则抛出该异常。还有其他情况会抛出此异常,但根据我的经验,这可能是因为未实现公共(public)空构造函数。

关于java - 亚马逊云数据库 : Could not unconvert attribute error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47926783/

相关文章:

java - 如何使用 BouncycaSTLe Java 将 PGP 公钥存储和读取为字符串?

amazon-web-services - 我们如何对AWS CDK代码进行单元测试?我们应该吗?

java - 如何从命令行调用带有 'java' 的 groovy

java - 在 Java EE 7 中通过 id 查找 websocket session

java - 尝试运行 Google Speedtracer 仪表板

python - 如何将 JSON 文件读入 Dataframe?

javascript - Photoshop 脚本数组到 json

javascript - 如何以 JSON 或 CSV 格式写入数据?

node.js - nodejs - 永远扫描目录以查找新文件

amazon-web-services - 指定 OpenSSL 配置文件时出错