Home > database >  JsonNode.get("") returns null value. I want to take "name" and "forks"
JsonNode.get("") returns null value. I want to take "name" and "forks"

Time:06-28

    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

CodePudding user response:

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

  • Related