1

I am using Jackson and I want to replace a value of my json string but I am not sure how should I do it. I have a json string like:

        "body": {
            "name": "oldname",
            "label": "1234"}

I would like to change the value of name to have my json like:

        "body": {
            "name": "newname",
            "label": "1234"}

so I have:

JsonNode parser = objectMapper.readTree(reader);
JsonNode body = parser.path("body");
String newName = "newname";

with using

body.path("name").asText().replace("oldname","newname");

it does not work.

How I can do it?

1 Answers1

2

You can do like: ((ObjectNode) body).put("name", newName);

  • body.path("name").asText().replace("oldname","newname"),

  • here you just replace operation on the string returned by asText() method. It does not modify our input json.

    ObjectMapper objectMapper = new ObjectMapper(); JsonNode parser = objectMapper.readTree(json); JsonNode body = parser.path("body"); String newName = "newname";

    ((ObjectNode) body).put("name", newName); // body.path("name").asText().replace("name", "newname");

    System.out.println(body);

Further Read: How to modify JsonNode in Java?

Dharman
  • 30,962
  • 25
  • 85
  • 135