客户端(改造)要求存储在服务器(Rest api)上的所有技能,该服务器从Skill
数据库表中以JSON数组的形式返回技能列表。
我想在客户处使用List<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());
}
});
ApiClient.java
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
}
]
如何获取列表?
答案 0 :(得分:0)
对于此转换,您应该使用TypeReference
List<Skill> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Skill>>(){});