gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:58:08 25 4
gpt4 key购买 nike

客户端(Retrofit)请求存储在服务器(Rest api)中的所有技能,这会从 Skill 返回 JSON 数组形式的技能列表。数据库表。

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

这是我的代码:

Controller 类(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(客户端):

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
}
]

如何获取列表?

最佳答案

对于此转换,您应该使用 TypeReference

List<Skill> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Skill>>(){});

关于java - 如何将改造 JSON 响应转换为列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com