Skip to content
Advertisement

JsonNode.get(“”) returns null value. I want to take “name” and “forks” from json on code

    RestTemplate restTemplate = new RestTemplate();
    String resourceUrl = "https://api.github.com/orgs/engineyard/repos"; //json address
    String response = restTemplate.getForObject(resourceUrl,String.class);
    ObjectMapper mapper = new ObjectMapper(); //mapper
    JsonNode jsonTree = mapper.readTree(response); //JsonNode
    System.out.println(jsonTree.get("name")); //null

I am trying to get all “name” and “forks” from this json URL enter link description here

Advertisement

Answer

public static void main(String[] args) throws Exception {

    RestTemplate restTemplate = new RestTemplate();
    String resourceUrl = "https://api.github.com/orgs/engineyard/repos";
    String response = restTemplate.getForObject(resourceUrl, String.class);
    ObjectMapper mapper = new ObjectMapper();

    JsonNode rootNode = mapper.readTree(response);

    System.out.println("All 'name's, including searching in child json objects");
    System.out.println("----------------------------------------------------");
    for (var val : rootNode.findValues("name")) {
        System.out.println(val);
    }

    System.out.println("Get 'name's only from first child nodes of the root");
    System.out.println("----------------------------------------------------");
    for (JsonNode firstNode : rootNode) {
        System.out.println(firstNode.path("name").asText());
    }
}

Replace name string with forks to get results for forks

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement