David Findlay David Findlay - 5 months ago 16
Java Question

Storing JSON Object in Key Value Field

I have a data structure to store some data in that accepts very specific JSON structure:

{ "NVPS": [ "NAME": "formData", "VALUE" : "myData" ] }

I'm serialising a large object that contains sub-objects into a string which I'm putting in the value field - replaces "myData" above.

// Serialise the form object
Map<String, String> formData = new HashMap<String, String>();
String foJson = JsonUtils.serializeJson(formObject); // returns a serialised version of formObject
formData.put("NAME", "formData");
formData.put("VALUE", foJson);

String storeJson = JsonUtils.serializeJson(formData);
storeJson = "{\"NVPS\":[" + storeJson + "]}";


Can anyone suggest a less ugly way I might be able to do this? I'm particularly not that happy with the last line where I create a JSON string by hand.

Here is the serializeJson() function from JsonUtils:

public static String serializeJson(Object dto) {
String result = null;
try {
ObjectWriter writer = mapper.writer();
result = writer.writeValueAsString(dto);
} catch (Exception e) {
String errorMsg = "Exception in serializeJson input= " + dto;
logger.error(JSON_UTILS_DEBUG_TEXT + errorMsg);
throw new RuntimeException(e);
}
return result;
}


It's using Jackson's ObjectWriter com.fasterxml.jackson.databind.ObjectWriter.

How can I clean up the first block of code?

Answer

Be aware that { "NVPS": [ "NAME": "formData", "VALUE" : "myData" ] } is not a valid JSON.


For valid JSON, you can try:

ObjectMapper mapper = new ObjectMapper();

ArrayNode arrayNode = mapper.createArrayNode();
arrayNode.addObject().put("NAME", "formData");
arrayNode.addObject().put("VALUE", "myData");

ObjectNode rootNode = mapper.createObjectNode();
rootNode.set("NVPS", arrayNode);

String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);

It will give you:

{
  "NVPS" : [ {
    "NAME" : "formData"
  }, {
    "VALUE" : "myData"
  } ]
}

You also can try:

ObjectMapper mapper = new ObjectMapper();

ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("NAME", "formData");
objectNode.put("VALUE", "myData");

ObjectNode rootNode = mapper.createObjectNode();
rootNode.set("NVPS", objectNode);

String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);

And the result will be:

{
  "NVPS" : {
    "NAME" : "formData",
    "VALUE" : "myData"
  }
}