Search code examples
javaapijerseyjersey-client

How to filter json result using java jersey


How to filter the Json result to get the particular fields. Can any one help me to overcome this confusion. Below is the java programming code using jersey client. This program use virus total API key to fetch the data from the virus total. I got the result in Json format and my aim to filter the Json result and get particular fields rather than all fields

public static void main(String[] args) 
    {
        String ip = "13.57.233.180"; 

        Client client = Client.create();

        WebResource resource = client.resource("https://www.virustotal.com/vtapi/v2/ip-address/report?ip="+ip+"&apikey="+API_KEY);

        ClientResponse response = resource.accept("appliction/json").get(ClientResponse.class);

        if(response.getStatus() != 200)
        {
            throw new RuntimeException("Failed Error Code : "+response.getStatus());
        }

        String output = response.getEntity(String.class);
        System.out.println("");
        System.out.println("Output from the server");
        System.out.println("");
        System.out.println(output);
    }

I got the output as

{
    "country": "US",
    "response_code": 1,
    "detected_urls": [],
    "resolutions": [
        {
            "last_resolved": "2018-01-28 00:00:00",
            "hostname": "ec2-13-57-233-180.us-west-1.compute.amazonaws.com"
        }
    ],
    "verbose_msg": "IP address in dataset"
}

And I need to do filter in that result. I mean I need only country and verbose message fields. please suggest me how to overcome with this problem?


Solution

  • First of all, please correct the resouse type in your code as there is a mistake in the spelling of application/json

    You can get your data into a Map/Hashmap using Jackson for Java. Add this dependency in your code for Jackson Code:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
    </dependency>
    

    Then add the following lines to your code:

    String output = response.getEntity(String.class);
    Map<String, Object> map = new ObjectMapper().readValue(output,HashMap.class);
    System.out.println("Country: " + map.get("country"));
    System.out.println("Verbose Message: " + map.get("verbose_msg"));
    

    This will fetch your data from String json (output) and map it on your hashmap.

    I hope this is the solution to your problem. Thanks.