Home > Software engineering >  Access json nested element directly in java
Access json nested element directly in java

Time:08-06

I have json string i want to direclty access element like childMap4.childMap3.ch3Name and my json string is i am not able find proper solutions.

{
  "is working": true,
  "childMap4": {
    "childMap3": {
      "childMap2": {
        "childMap1": {
          "ch1Name": "childMap1"
        },
        "ch2Name": "childMap2"
      },
      "ch3Name": "childMap3 testing"
    },
    "ch4Name": "childMap4"
  },
  "prName": "parentMap",
  "salary": 800.23,
  "prName2": "parentMap field 2",
  "age": 24
}

CodePudding user response:

If you just want to extract the value, you should take a look at JsonPath. Just use the method JsonPath.read([json_object], [expression]) with expression $.childMap4.childMap3.ch3Name.

Another approach would be to create proper mapping class and deserialize JSON string with a library like Jackson, but if you want just single field value taht would be an overkill.

CodePudding user response:

JsonNode jsonNode = mapper.convertValue(Obj, JsonNode.class);

jsonNode.path("childMap4").path("childMap3").path("ch3Name").toString();

  • Related