【问题标题】:使用 Gson 解析 JSON 数据
【发布时间】:2022-01-23 15:42:49
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java json gson httprequest httpclient


    【解决方案1】:

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

    效果很好!

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        您的 Food.class 应如下所示:

        public class Food {
        
        private String description;
        
        public String getDescription() {
            return description;
         }
        
        public void setDescription(String description) {
            this.description = description;
         }
        }
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-27
          • 1970-01-01
          • 1970-01-01
          • 2011-02-12
          • 2012-01-02
          相关资源
          最近更新 更多