You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于通过jsonschema2pojo生成Retrofit可用POJO的技术咨询

验证Retrofit POJO类正确性及使用指南

Hey there! Let’s walk through how to make sure your auto-generated POJO (from jsonschema2pojo) is ready for Retrofit, plus how to use it effectively with your game data JSON.

一、先确认POJO的正确性

1. 字段与类型匹配检查

First up, double-check that every field in your POJO lines up perfectly with the JSON structure:

  • id: The JSON uses a number (1942) — using long or Integer is safer than int (avoids overflow for larger IDs).
  • name: Straightforward String type, no surprises here.
  • first_release_date: That’s a millisecond timestamp, so it should be a long (not int! Int can’t handle timestamps this big).
  • screenshots: This is an array of objects, so your POJO should have a List<Screenshot> field, and the nested Screenshot class should have a url String field.

Also, if jsonschema2pojo converted snake_case JSON fields to camelCase (like first_release_date → firstReleaseDate), make sure each field has the @SerializedName annotation. For example:

@SerializedName("first_release_date")
private long firstReleaseDate;

This is critical for Retrofit to map the JSON keys correctly to your POJO fields.

2. 序列化/反序列化测试

The best way to confirm your POJO works is to test it with Gson (Retrofit’s go-to converter). Write a quick test snippet:

// Your sample JSON string
String testJson = "[{\"id\":1942,\"name\":\"The Witcher 3: Wild Hunt\",\"first_release_date\":1431993600000,\"screenshots\":[{\"url\":\"//images.igdb.com/igdb/image/upload/t_thumb/z5t0yuhyiiui1ickwhgj.jpg\"}]}]";

// Convert JSON to POJO
Gson gson = new Gson();
List<Game> gameList = gson.fromJson(testJson, new TypeToken<List<Game>>() {}.getType());

// Verify values
System.out.println("Game Name: " + gameList.get(0).getName());
System.out.println("First Screenshot URL: " + gameList.get(0).getScreenshots().get(0).getUrl());

// Convert back to JSON to check consistency
String convertedBack = gson.toJson(gameList);
// Compare convertedBack with your original JSON (ignore whitespace differences)

If all values print correctly and the converted JSON matches the original, your POJO is good to go.

二、在Retrofit中使用这个POJO

1. 配置Retrofit与转换器

First, make sure you have the right dependencies in your build.gradle (Module level):

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

Then set up your Retrofit instance:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://your-api-base-domain.com/") // Replace with your actual API base URL
    .addConverterFactory(GsonConverterFactory.create())
    .build();

2. 定义API接口

Create an interface to define your API endpoints. Since your JSON is a list of games, your endpoint should return a Call<List<Game>>:

public interface GameApiService {
    @GET("games") // Replace with your actual endpoint path
    Call<List<Game>> getGames();
}

If you need to add query parameters (like filtering games), you can add @Query annotations, e.g., @GET("games") Call<List<Game>> getGames(@Query("genre") String genre);

3. 发起网络请求

Now make the call and handle the response:

GameApiService apiService = retrofit.create(GameApiService.class);
Call<List<Game>> call = apiService.getGames();

call.enqueue(new Callback<List<Game>>() {
    @Override
    public void onResponse(Call<List<Game>> call, Response<List<Game>> response) {
        if (response.isSuccessful()) {
            List<Game> games = response.body();
            // Do something with your game data!
            for (Game game : games) {
                Log.d("Game Info", "Name: " + game.getName());
                // Don't forget to fix the screenshot URLs — they're missing the https: prefix
                for (Screenshot screenshot : game.getScreenshots()) {
                    String fullImageUrl = "https:" + screenshot.getUrl();
                    Log.d("Screenshot URL", fullImageUrl);
                }
            }
        } else {
            // Handle unsuccessful response (e.g., 404, 500)
            Log.e("API Error", "Response code: " + response.code());
        }
    }

    @Override
    public void onFailure(Call<List<Game>> call, Throwable t) {
        // Handle network errors (e.g., no internet)
        Log.e("Network Error", "Error message: " + t.getMessage());
    }
});

三、几个关键注意事项

  • Fix screenshot URLs: The JSON returns URLs starting with // — you need to prepend https: to make them valid, otherwise they won’t load.
  • Timestamp conversion: If you want to use a Date or LocalDateTime instead of a raw long for first_release_date, you can add a helper method to your POJO:
public LocalDateTime getFirstReleaseDateAsDateTime() {
    return Instant.ofEpochMilli(firstReleaseDate).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
  • Null safety: If your API might return null values for fields (e.g., a game without screenshots), use wrapper types like Integer instead of int to avoid null pointer exceptions.

内容的提问来源于stack exchange,提问作者Medy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:55:14