Tibberzz Tibberzz - 3 years ago 199
Java Question

Deserializing Primary Key Value with Underscore: Unexpected character Expected space separating root-level values

In Java, using the Jackson ObjectMapper, I'm trying to deserialize a dynamo db object being read from a dynamo db stream.

I first call:

record.getDynamodb().getNewImage().get("primaryKey").getS().toString()

to get the primaryKey value of "1_12345" back from the stream.

I then use it in the object mapper to create a new instance of the Metrics object with the primaryKey member set:
objectMapper.readValue("1_12345", Metrics.class);


The problem is I get an exception on that call:
Unexpected character ('_' (code 95)): Expected space separating root-level values


Metrics.class is a simple POJO with no constructor. I'm wondering if I need any special annotations or escape characters in my readValue call. I can't seem to find any clear indications on what the solution is in the case of this error.

(Side note - the reason I can't parse it straight from the json is because the json's structure when it's parsed from the stream isn't straightforward, a value looks like this, S indicating String, N for number etc:
{primaryKey={S: 1_12345,}, rangeKey={N: xxx}... etc. }
)

Answer Source

Thank you, that was the problem, the readValue() call takes a String in the format of JSON. The solution was to convert the dynamo streamed image into lists & maps (using the dynamodbv2 libs) until it was in the correct format as below:

Map<String, AttributeValue> newImage = record.getDynamodb().getNewImage(); 
List<Map<String, AttributeValue>> listOfMaps = new ArrayList<Map<String, AttributeValue>>(); 
listOfMaps.add(newImage); 
List<Item> itemList = InternalUtils.toItemList(listOfMaps); 
for (Item item : itemList) { 
  String json = item.toJSON(); 
  Metrics metric = objectMapper.readValue(json, Metrics.class); 
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download