[英]How to convert retrofit JSON response into List?
Client (Retrofit) requested all skills stored at server (Rest api), which returns a list of skills as JSON array from the Skill
Database Table.客户端 (Retrofit) 请求存储在服务器 (Rest api) 中的所有技能,它从
Skill
数据库表中以 JSON 数组的形式返回技能列表。
I want List<Skill>
(Skill is a POJO class) at client.我想要
List<Skill>
(Skill 是一个 POJO 类)在客户端。 How can I convert Json response into list.如何将 Json 响应转换为列表。
here is my code:这是我的代码:
method of controller class(Server):控制器类(服务器)的方法:
@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 (Client): 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 SkillApiService.java
public interface SkillApiService {
@GET("/skill/all")
Call<Skill> getAllSkills();
}
JsonResponse: It gives the skill table values. JsonResponse:它给出了技能表值。
[
{
"skillid":1,
"name":"äbc",
"imagePath":"<path>",
"imageName":"abc.png",
"imagesize":200
},
{
"skillid":2,
"name":"xyz",
"imagePath":"<path>",
"imageName":"xyz.png",
"imagesize":200
}
]
How do I get the List?我如何获得名单?
对于此转换,您应该使用TypeReference
List<Skill> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Skill>>(){});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.