1

I have some arbitrary Json and I want to replace some of the text fields with objects. The text fields have a certain pattern, for example, say they start with a dollar sign $. I have no idea in advance what the keys are.

The object I want to replace it with is a Pojo probably a Map or List, which can be easily serialized to Json

For example

{
   "key1" : "some value",
   "key2" : "$replaceMe",
   "key3" : {
       "key4" : "more complex",
       "key5" : "$andMe"
}

So after the replacement, the object would look something like this

{
   "key1" : "some value",
   "key2" : {},
   "key3" : {
       "key4" : "more complex",
       "key5" : {}
}

where {} represents the new object that replaced the string that was previously there

I figured out several ways to traverse the tree, but can't figure out a good way to keep track of the objects to be replaced and how to replace them.

Peter Kronenberg
  • 878
  • 10
  • 32

1 Answers1

1

You can iterate over the JsonNode nodes of your json file checking the child nodes of every parent node : you can check if there are children nodes representing basic JSON String value with theJsonNode#isTextual method and if their text starts with the dollar sign like below:

ObjectMapper mapper = new ObjectMapper();
//with a generic parent jsnode and one child node of it
if (child.isTextual() && child.asText().startsWith("$")) {
    //delete the old text value and create an empty objectnode
    ((ObjectNode)parent).set(fieldName, mapper.createObjectNode());
}

For the creation of an empty ObjectNode child you can use the ObjectMapper#createObjectNode method like I have done above.

dariosicily
  • 4,239
  • 2
  • 11
  • 17