0

I am receiving JSON from AWS DynamoDB. I am having trouble getting to the nested items.

Im trying to retrieve two fields, 'session_nr' and 'session_type_name', from this JSON:

{content={S: {"session_nr":"PG8","session_name":"Title of this session","session_type_name":"blah blah name type"},}}

This is how each record appears. So far, this is the code I have, using a AWS ScanResult:

ScanRequest scanRequest = new ScanRequest()
                      .withTableName("table_name")
                      .withFilterExpression("field = :val")
                      .withProjectionExpression("content")
                      .withExpressionAttributeValues(expressionAttributeValues);

        ScanResult scanResult = client.scan(scanRequest);


        for (Map<String, AttributeValue> item : scanResult.getItems()) {

            System.out.println(item);

        }

2 Answers 2

1

Here is what works. Thanks @notionquest

ObjectMapper mapper = new ObjectMapper();
        for (Map<String, AttributeValue> item : scanResult.getItems()) {

            Map<String, Object> map = mapper.readValue(item.get("content").getS(), new TypeReference<Map<String,Object>>(){});
            System.out.println(map.get("session_nr"));
        }
Sign up to request clarification or add additional context in comments.

Comments

0

The JSON values can be get as follows. I have used ObjectMapper class from Jackson library to convert JSON to Map.

Please add code to handle the exception accordingly.

Map<String, Object> jsonMap = objectMapper.readValue(item.get("content").getS(), Map.class);
System.out.println(jsonMap.get("session_nr"));
System.out.println(jsonMap.get("session_name"));

Jackson Dependency:-

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.1</version>
</dependency>

1 Comment

I am already receiving a map in the return. In any case, trying your suggestion, get an error with this line: Map<String, Object> map = ObjectMapper.class.readValue(item.get("content").getS(), new TypeReference<Map<String,Object>>(){});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.