12

I have this json file:

{
  "gateway_name": "gateway1",
  "fields": [
    {"name":"Code", "value":""},
    {"name":"PaymentId", "value":""},
    {"name":"RefNo", "value":""}
  ]
}

I trying to parse this file with Jackson object mapper and iterate through the fields array. What i want to achieve is when name equals to RefNo, manipulate the value to 1112, so it will become:

{
  "gateway_name": "gateway1",
  "fields": [
    {"name":"Code", "value":""},
    {"name":"PaymentId", "value":""},
    {"name":"RefNo", "value":"1112"}
  ]
}

How do i check the field value and set the value to 1112?

What i tried until this point is:

  Resource resource = new ClassPathResource("gateway-fields.json");  //read from json file
  JsonFactory jsonFactory = new JsonFactory();
  ObjectMapper objectMapper = new ObjectMapper(jsonFactory);

  JsonNode arrayNode = objectMapper.readTree(resource.getFile()).get("fields");

  if (arrayNode.isArray()) {
      for (JsonNode jsonNode : arrayNode) {
          JsonNode nameFieldNode = jsonNode.get("name");
          JsonNode valueFieldNode = jsonNode.get("value");

          //Stcuked here
          IF nameFieldNode is "RefNo"
          THEN SET valueFieldNode to "1112"
      }
  }
hades
  • 4,294
  • 9
  • 46
  • 71
  • 2
    and what is your question ? – Ravi Aug 14 '18 at 07:02
  • [textValue](https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/JsonNode.html#textValue()) – Scary Wombat Aug 14 '18 at 07:04
  • 1
    Why don't you map your JSON data structure to actual Java classes, with named and typed fields, instead of manipulating JsonNodes? It would make the code so much cleaner: `Gateway geateway = objectMapper.readValue(json, Gateway.class); gateway.getFieldNamed("RefNo").setValue("1112");`. Isn't that much clearer? – JB Nizet Aug 14 '18 at 07:10
  • @JBNizet yeah you got the point, will consider that, thanks for the suggestion. – hades Aug 14 '18 at 07:26

1 Answers1

15

Compare with name and update that json element.

Resource resource = new ClassPathResource("gateway-fields.json");  //read from json file
      JsonFactory jsonFactory = new JsonFactory();
      ObjectMapper objectMapper = new ObjectMapper(jsonFactory);

      JsonNode arrayNode = objectMapper.readTree(resource.getFile()).get("fields");

      if (arrayNode.isArray()) {
          for (JsonNode jsonNode : arrayNode) {
              String nameFieldNode = jsonNode.get("name").asText();    
              if("RefNo".equals(nameFieldNode)){
                     ((ObjectNode)jsonNode).put("name", "1112");
              }
          }
      }
Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48