关于通过jsonschema2pojo生成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) — usinglongorIntegeris safer thanint(avoids overflow for larger IDs).name: StraightforwardStringtype, no surprises here.first_release_date: That’s a millisecond timestamp, so it should be along(notint! Int can’t handle timestamps this big).screenshots: This is an array of objects, so your POJO should have aList<Screenshot>field, and the nestedScreenshotclass should have aurlString 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 prependhttps:to make them valid, otherwise they won’t load. - Timestamp conversion: If you want to use a
DateorLocalDateTimeinstead of a rawlongforfirst_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
Integerinstead ofintto avoid null pointer exceptions.
内容的提问来源于stack exchange,提问作者Medy

