[英]how to get Json objects from json array and use them with model class
我想使用gson庫將接收到的json數據鏈接到我的pojo類。我使用了volley庫來接收數據。當我從pojo類中調用getter方法時,我應該怎么做才能獲取接收到的json數據。
我的Json數據是這種格式。
{
"vichList":[ {
id=1,
username="abc....},
{....},
]
}
我想將此json數據放入我的pojo類中。
Vich.java
public class GetfeedResponse {
private List<Vich> vichList;
public List<Vich> getVichList() {
return vichList;
}
public void setVichList(List<Vich> vichList) {
this.vichList = vichList;
}
}
Vich.java
public class Vich {
private int id;
private String username;
private String full_name;
private String createdAt;
private int vich_id;
private String vich_content;
private String city;
private int like_count;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public int getVich_id() {
return vich_id;
}
public void setVich_id(int vich_id) {
this.vich_id = vich_id;
}
public String getVich_content() {
return vich_content;
}
public void setVich_content(String vich_content) {
this.vich_content = vich_content;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getLike_count() {
return like_count;
}
public void setLike_count(int like_count) {
this.like_count = like_count;
}
}
在這里,我得到了使用凌空庫的json響應。
httpUtil.getrequest(url,this,new VolleyCallback(){
@Override
public void onSuccess(String result){
GetfeedResponse getfeedResponse = new GetfeedResponse();
// for(Vich vich : getfeedResponse.getVichList()){
// }
Log.d("Response Result:",result);
}
我如何從json數組中獲取對象並在pojo類的幫助下使用它們?
使用Gson
在gradle中添加以下依賴項:
implementation 'com.google.code.gson:gson:2.8.5'
在你的onSuccess()
GetfeedResponse getfeedResponse=new Gson().fromJson(result, GetfeedResponse.class);
如果您想使用Volley和POJO,最好使用自定義GSON請求。 檢查此鏈接: 排球的定制GSON請求
GSON:
GetfeedResponse parsed = new Gson().fromJson(response, GetfeedResponse.class);
傑克遜:
GetfeedResponse parsed = new ObjectMapper().readValue(response, GetfeedResponse.class);
此外,如果您只想轉換Vich項目列表(並且相應地剝離了JSON),則可以執行以下操作:
[ {
id=1,
username="abc....},
{....},
]
List<Vich> viches = Arrays.asList(new Gson().fromJson(vichItemsJson, Vich[].class));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.