How to clone a json content with some modifications using jackson fasterxml

36 views Asked by At

Suppose we create a json as a string constructed like this;

StringWriter writer = new StringWriter();
final JsonGenerator json = mapper.getFactory().createJsonGenerator(writer);
// construct the content using various json.write* functions
json.flush();
String content = writer.toString();

Now I want to clone this content into another json but with some modifications (say override some fields). Given the below restrictions how can I achieve this?

  1. above content creation is extremely lengthy and complex
  2. it doesn't use schemas
  3. it doesn't have Java objects representing each field/node
  4. must preserve the order of fields
1

There are 1 answers

0
Hemant Metalia On

To clone JSON content with some modifications using Jackson FasterXML while preserving the order of fields and given the restrictions you mentioned, you can follow these steps:

Parse the original JSON content into a JsonNode. Create a new ObjectNode to make modifications. Apply the desired modifications to the new ObjectNode. Serialize the modified ObjectNode back into JSON.

       // Create Jackson ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // Parse the original JSON content into a JsonNode
        JsonNode originalNode = mapper.readTree(originalJson);

        // Create a new ObjectNode to make modifications
        ObjectNode modifiedNode = mapper.createObjectNode();

        // Copy the original content to the modified node
        originalNode.fields().forEachRemaining(entry -> {
            modifiedNode.set(entry.getKey(), entry.getValue());
        });

        // Apply modifications (override some fields)
        modifiedNode.put("field1", "new_value1");