我是一个完全的初学者,当谈到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#/
3条答案
按热度按时间cotxawn71#
因此,我仔细查看了api文档,发现类应该是
并且只打印说明:
效果非常好!
omtl5h9j2#
尝试在
Food
类中添加setters方法以获取说明文本,然后尝试使用以下print语句打印description
:System.out.println(food.getDescription());
7vux5j2d3#
您的Food.class应该如下所示:
然后通过get方法获取描述。