Client (Retrofit) requested all skills stored at server (Rest api), which returns a list of skills as JSON array from the Skill
Database Table.
I want List<Skill>
(Skill is a POJO class) at client. How can I convert Json response into list.
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):
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: It gives the skill table values.
[
{
"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>>(){});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.