使用Gson解析JSON数据

wfauudbj  于 2022-11-06  发布在  其他
关注(0)|答案(3)|浏览(250)

我是一个完全的初学者,当谈到Http请求,json等。我试图通过Java的HttpClient和HttpRequest访问食物数据。数据包含了很多信息,但我只想显示“描述”。下面是我的食物类:

public class Food {
    String description;
}

和我的请求:

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);
    }
}

现在,第一个print语句提供了所有数据:

{"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"

这还不是全部,但您可以在所有数据的这一部分的末尾找到描述部分。问题是第二个print语句没有打印描述,而是打印了null。哪里出了问题?Api文档:https://fdc.nal.usda.gov/api-spec/fdc_api.html#/

cotxawn7

cotxawn71#

因此,我仔细查看了api文档,发现类应该是

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

class SearchResultFood {
    String 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);
        }

效果非常好!

omtl5h9j

omtl5h9j2#

尝试在Food类中添加setters方法以获取说明文本,然后尝试使用以下print语句打印description
System.out.println(food.getDescription());

7vux5j2d

7vux5j2d3#

您的Food.class应该如下所示:

public class Food {

private String description;

public String getDescription() {
    return description;
 }

public void setDescription(String description) {
    this.description = description;
 }
}

然后通过get方法获取描述。

相关问题