Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - Iterate array and manipulate its value [duplicate]

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"
      }
  }
like image 612
hades Avatar asked Mar 05 '23 15:03

hades


1 Answers

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");
              }
          }
      }
like image 87
Kaustubh Khare Avatar answered Mar 17 '23 06:03

Kaustubh Khare