[英]How to convert retrofit JSON response into List?
客戶端 (Retrofit) 請求存儲在服務器 (Rest api) 中的所有技能,它從Skill
數據庫表中以 JSON 數組的形式返回技能列表。
我想要List<Skill>
(Skill 是一個 POJO 類)在客戶端。 如何將 Json 響應轉換為列表。
這是我的代碼:
控制器類(服務器)的方法:
@GetMapping(path = "/skill/all")
public List<Skill> getAllSkills() {
List<Skill> skills = skillRepo.findAll();
for (Skill s : skills) {
String path = s.getImagePath();
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path(IMAGEPATH+path)
.toUriString();
s.setImagePath(fileDownloadUri);
}
return skills;
}
SkillActivity.java(客戶端):
Retrofit retrofit =apiClient.getRetrofitInstance();
SkillApiService skillApiService = retrofit.create(SkillApiService.class);
Call<Skill> call = skillApiService.getAllSkills();
call.enqueue(new Callback<Skill>() {
@Override
public void onResponse(Call<Skill> call, Response<Skill> response) {
if(response.isSuccessful() && response.body() != null){
List<Skill> listSkills = new ArrayList<>();
//here in List<Skill>, I want to store response, which will be pass in recycerview adapter below
recyclerView = findViewById(R.id.recyclerView_skill);
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),3));
recyclerView.setAdapter(new RecyclerViewAdapter(getApplicationContext(), listSkills));
}
}
@Override
public void onFailure(Call<Skill> call, Throwable t) {
Log.d("onFailure",t.getMessage());
}
});
客戶端程序
public Class ApiClient{
private static final String BASE_URL = “http://ip:port”;
public static Retrofit getRetrofitInstance(){
return new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(BASE_URL).build();
}
SkillApiService.java
public interface SkillApiService {
@GET("/skill/all")
Call<Skill> getAllSkills();
}
JsonResponse:它給出了技能表值。
[
{
"skillid":1,
"name":"äbc",
"imagePath":"<path>",
"imageName":"abc.png",
"imagesize":200
},
{
"skillid":2,
"name":"xyz",
"imagePath":"<path>",
"imageName":"xyz.png",
"imagesize":200
}
]
我如何獲得名單?
對於此轉換,您應該使用TypeReference
List<Skill> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Skill>>(){});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.