Java - 如何在 OkHttpClient 上使用模型获取 api 数据

问题描述 投票:0回答:1

我想使用 OkHttpClient 从 api 中提取数据。我想要提取的示例数据:https://dummyjson.com/products 我创建了两个模型。我认为我正确地创建了模型。你认为我做错了什么?我为模型字段创建了 getter 和 setter 方法。我这里没有添加。

public class TestModel {
    public class ProductList {
        private List<Product> products;
        private int total;
        private int skip;
        private int limit;
    }
    public class Product {
        private int id;
        private String title;
        private String description;
        private double price;
        private double discountPercentage;
        private double rating;
        private int stock;
        private String brand;
        private String category;
        private String thumbnail;
        private List<String> images;
    }
}

当我使用 OkHttpClient 编写下面的代码时,出现空错误。我不认为数据为空。

private final OkHttpClient client = new OkHttpClient();

    public void GetFromServer(String _serviceUrl) throws Exception {
        String absoluteUrl = baseUrl + "/" + _serviceUrl;
        Request request = new Request.Builder()
                .url(absoluteUrl)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                Logging.Error("GetFromServer is Failure. Endpoint : " + absoluteUrl + " Error Message : " + e.getMessage());
                e.printStackTrace();
            }
            @Override public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (response.isSuccessful()) {
                        String json = response.body().string();

                        Gson gson = new Gson();
                        TestModel.ProductList productList = gson.fromJson(json, TestModel.ProductList.class);

                        List<TestModel.Product> products = productList.getProducts();
                        for (TestModel.Product product : products) {
                            System.out.println("Product Title: " + product.getTitle());
                            System.out.println("Description: " + product.getDescription());
                           
                        }
                    }
                    else {
                        throw new IOException("Unexpected code " + response);
                    }
                }
            }
        });
    }
java android okhttp
1个回答
0
投票

您应该将产品类别标记为静态,例如:

public static class Product
© www.soinside.com 2019 - 2024. All rights reserved.