繁体   English   中英

用 Gson 解析 JSON 数据

[英]Parsing JSON Data with Gson

对于 Http 请求、json 等,我是一个完整的初学者。我正在尝试通过 Java 的 HttpClient 和 HttpRequest 访问食物数据。 数据包含很多信息,但我只想显示“描述”。 这是我的食物 Class:

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

现在第一个打印语句给了我所有的数据:

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

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

所以我仔细查看了 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);
        }

效果很好!

尝试在Food class 中添加设置方法以获取描述文本,然后尝试使用以下打印语句打印description

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

你的 Food.class 应该是这样的:

public class Food {

private String description;

public String getDescription() {
    return description;
 }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM