Isvoran Andrei
Isvoran Andrei

Reputation: 478

How to read a nested value in a JSON using Jackson

I have a json structure like this:

{
  "version": 1.0,
  "object": {
    "a1": "a2",
    "b1": "b2
  },
  "deploy": {
    "applicationName": "app",
    "namespace": "com.abc.xyz"
    ...
  }
}

The ... means the JSON continues more. I want to retrieve the namespace from this JSON. My code looks like this:

JsonNode rootNode = new ObjectMapper().readTree(json);
var result = rootNode.at("/deploy/namespace");

However, with this code, result will always ""

I've tried different paths but I'm always getting an empty String. Any help?

Upvotes: 1

Views: 2306

Answers (1)

robertobatts
robertobatts

Reputation: 967

The problem is that at return a JsonNode, so you need to access it:

JsonNode rootNode = new ObjectMapper().readTree(json);
var result = rootNode.at("/deploy/namespace").asText();

Otherwise, you can also access it in this way:

JsonNode rootNode = new ObjectMapper().readTree(json);
var result = rootNode.path("deploy").path("namespace").asText();

Upvotes: 3

Related Questions