Home > Enterprise >  Parsing JSON Data with Gson
Parsing JSON Data with Gson

Time:12-22

I am a complete beginner when it comes to Http request, json etc. I am trying to access food data through Java's HttpClient and HttpRequest. The data contains alot of information but I am trying only to display the "description". Here is my Food Class:

public class Food {
    String description;
}

and my request:

public class Test {
    
    public static void main(String[] args) throws IOException, InterruptedException {
        // create a client
        HttpClient client = HttpClient.newHttpClient();

        // create a request
        HttpRequest request = HttpRequest.newBuilder()
            .GET()
            .uri(
            URI.create("https://api.nal.usda.gov/fdc/v1/foods/search?query=mango&pageSize=1&pageNumber=1&api_key=...")
            ).build();

        // use the client to send the request
        HttpResponse<String> response = client.send(request,HttpResponse.BodyHandlers.ofString());
        Food food = new Gson().fromJson(response.body(), Food.class);
        // the response:
        System.out.println(response.body());
        System.out.println(food.description);
    }
}

Now the first print statement gives me all the data:

{"totalHits":11,"currentPage":1,"totalPages":11,"pageList":[1,2,3,4,5,6,7,8,9,10],"foodSearchCriteria":{"dataType":["Survey (FNDDS)"],"query":"mango","generalSearchInput":"mango","pageNumber":1,"numberOfResultsPerPage":50,"pageSize":1,"requireAllWords":false,"foodTypes":["Survey (FNDDS)"]},"foods":[{"fdcId":1102670,"description":"Mango, raw","lowercaseDescription"

and this is not even all, but you find the description part at the end of this fraction of all the data. The problem is the second print statement doesn't print the description, it prints null. What goes wrong? The Api documentation: https://fdc.nal.usda.gov/api-spec/fdc_api.html#/

CodePudding user response:

Try adding setters methods in Food class for getting description text and then try to print description with following print statement as,

System.out.println(food.getDescription());

CodePudding user response:

So I took a closer look at the api documentation and found that the classes should be

class Result {
    int totalHits;
    SearchResultFood[] foods;
}

class SearchResultFood {
    String description;
}

And to only print the description:

        Result result = new Gson().fromJson(response.body(), Result.class);
        // the response:
        //System.out.println(response.body());
        for(SearchResultFood s : result.foods) {
            System.out.println(s.description);
        }

which works perfectly!

  • Related