繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM