首页 > 解决方案 > 使用 Gson 和数据中的 JSONObject 从服务器解析数据

问题描述

我有一个从服务器收到的数据。

{
  "_id": "5a78263eab294307bebc2e6b",
  "userID": "PvIMsjink1UcrwXZ4gb899W5Kxo2",
  "name": "battery",
  "price": 22,
  "description": "t",
  "__v": 0,
  "boardVisibility": "MainBoard",
  "date": "2018-02-05T09:39:10.597Z",
  "picture": {
    "url": "https:\/\/firebasestorage.googleapis.com\/v0\/b\/bitbuy-bitbuy.appspot.com\/o\/user%2FPvIMsjink1UcrwXZ4gb899W5Kxo2%2FDepositphotos_59984669_s-2015.jpg?alt=media&token=a562fd6d-98ff-4fb8-ad93-c251a5016b0d",
    "name": "Depositphotos_32026397_m-2015.jpg"
  }
}

这是模型类:

   @SerializedName("_id")
    private String _id;
    @SerializedName("userID")
    private String userID;
    @SerializedName("name")
    private String name;
    @SerializedName("price")
    private double price;
    @SerializedName("description")
    private String description;
    @SerializedName("date")
    private String date;
    @SerializedName("picture")
    private JSONObject picture;

这是我将数据设置为ArrayList

userItemsArr = Gson().fromJson<List<UserItem>>(gsonObj.getJSONArray("docs").toString(), turnsType) as ArrayList<UserItem>

问题是picture响应中的值包含另一个 JSONObject,所以在我的模型类中我得到一个空的 JSONObject。

标签: androidkotlingson

解决方案


"picture": {
    "url": "https:\/\/firebasestorage.googleapis.com\/v0\/b\/bitbuy-bitbuy.appspot.com\/o\/user%2FPvIMsjink1UcrwXZ4gb899W5Kxo2%2FDepositphotos_59984669_s-2015.jpg?alt=media&token=a562fd6d-98ff-4fb8-ad93-c251a5016b0d",
    "name": "Depositphotos_32026397_m-2015.jpg"
  }

你应该纠正你的MODEL班级。

@SerializedName("picture")
@Expose
private Picture picture;

// 设置-获取方法

public Picture getPicture() {
return picture;
}

public void setPicture(Picture picture) {
this.picture = picture;
}

public class Picture {

@SerializedName("url")
@Expose
private String url;
@SerializedName("name")
@Expose
private String name;

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

您可以使用jsonschema2pojo.


推荐阅读