简体   繁体   中英

Converting DynamoDB JSON document to JSON object in Java

I am reading the backup DynamoDB S3 bucket which has format for DynamoDB Json.

I am trying to convert it into a normal Json without the AttributeValue.

Original String

{
  "id": {
    "s": "someString"
  },
  "name": {
    "b": "someByteBuffer"
  },
  "anotherId": {
    "s": "someAnotherString"
  },
  "version": {
    "n": "1"
  }
}

Trying to Convert to

{
  "id": "someString",
  "name": "someByteBuffer",
  "anotherId": "someAnotherString",
  "version": "1"
}

There are many answers which I referred to but it doesnt convert into normal Json, it gives me back the same Json.

Here is what I tried:

ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(inputJsonString);
final JacksonConverter converter = new JacksonConverterImpl();
Map<String, AttributeValue> map = converter.jsonObjectToMap(jsonNode);        

Item item = ItemUtils.toItem(map);

Gson gson = new Gson();
System.out.println(gson.toJson(item.asMap()));

Also, when I was debugging, I wasn't able to create the Map properly. Map would contain key as "id", value as AttributeValue. But the AttributeValue would contain the string inside its own Map<String, AttributeValue> instead of inside String s

I feel I am missing something while creating the Map. Any pointers?

References on Stackoverflow: Link 1 Link 2

Thanks,

Jay

What you're describing as the result sounds correct. If you look at the original JSON string, you have a list of key:value pairs where each value is another list of key:value pairs (length 1, but still a list).

To convert this to a single list of key:value pairs you need to write a map-reduce type of loop. Basically iterate the first map, take the key, then, from the second map (which is the value for the key you just recorded), just take the first entry's value (AttributeValue) and add that key:value pair into a new map ( Map<String, AttributeValue> , which you define before the loop). That map you can then convert to JSON and it will result in the JSON string that you were expecting.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM