DynamoDBMapper不转换属性错误

时间:2018-01-26 07:14:16

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

我从dynamoDb获得json,看起来像这样 -

{
    "id": "1234",
    "payment": {
        "payment_id": "2345",
        "user_defined": {
            "some_id": "3456"
            }
        }
}

我的目标是获取Java user_defined中的HashMap<String, Object>字段,因为user_defined字段可以包含任何用户定义的字段,这些字段在数据到达之前是未知的。一切正常,但我的DynamoDBMapper无法将user_defined字段转换为Java HashMap。它抛出了这个错误 -

Exception occured Response[payment]; could not unconvert attribute

这就是课程的样子 -

@DynamoDBTable(tableName = "PaymentDetails")
public class Response {

    private String id;

    public Response() {
    }

    private Payment payment = new Payment();

    @DynamoDBHashKey(attributeName="id")
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }

    public Payment getPayment() {
        return payment;
    }

    public void setPayment(Payment payment) {
        this.payment = payment;
    }

}

付款字段映射器 -

@DynamoDBDocument
public class Payment {
private String payment_id:
private HashMap<String, Object> user_defined;

public Payment() {}

public getPayment_id() {
    return payment_id;
}

public setPayment_id(String payment_id) {
    this.payment_id = payment_id;
}

@DynamoDBTypeConverted(converter = HashMapMarshaller.class)
    public HashMap<String, Object> getUser_defined() {
        return user_defined;
    }

    public void setUser_defined(HashMap<String, Object> user_defined) {
        this.user_defined = user_defined;
    }
}

HashMapMarshaller(只是为了检查Hashmap marshaller是否使用gson,我刚刚定义了一个Hashmap,输入一个值并将其返回,但似乎仍然没有工作) -

public class HashMapMarshaller implements DynamoDBTypeConverter<String, HashMap<String, Object>> {

    @Override
    public String convert(HashMap<String, Object> hashMap) {
        return new Gson().toJson(hashMap);
    }

    @Override
    public HashMap<String, Object> unconvert(String jsonString) {
        System.out.println("jsonString received for unconverting is " + jsonString);
        System.out.println("Unconverting attribute");
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("key", "value");

        return hashMap;

        //return new Gson().fromJson(jsonString, new TypeToken<HashMap<String, Object>>(){}.getType());
    }
}

Marshaller的方法到现在为止不适合我。它也没有打印出println中的任何一个。我还尝试使用@DynamoDBTyped(DynamoDBMapperFieldModel.DynamoDBAttributeType.M)并使用Map而非HashMap取代user_defined获取者无效。

我想了解如何将user_defined字段转换为Java HashMapMap。任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:0)

Make Map<String, Object> to Map<String, String>. It should work without any custom converters. Otherwise be specific about Map's value type. For example, Map<String, SimplePojo> should work. Don't forget to annotate SimplePojo class with @DynamoDBDocument.

With Object as a type of Map's value, DynamoDB will not able to decide which object it has to create while reading entry from DynamoDB. It should know about specific type like String, Integer, SimplePojo etc.