如何将改装 JSON 响应转换为列表?

How to convert retrofit JSON response into List?

客户端(Retrofit)请求存储在服务器(Rest api)的所有技能,其中 returns 来自 Skill 数据库 JSON 数组的技能列表 Table。

我想 List<Skill>(技能是 POJO class)在客户端。如何将 Json 响应转换为列表。

这是我的代码:

控制器方法class(服务器):

@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();
}

Json响应:它赋予技能 table 值。

[
    {
        "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>>(){});