如何将嵌套的JSON数组存储到模型中

时间:2018-11-04 02:19:27

标签: java android arrays gson

您好,所以我有一个名为Job的模型。该模型收集有关特定作业的所有信息。但是,数据库关系的布局方式意味着当我返回作业详细信息时,我得到了一个嵌套在作业对象内部的cargo数组。我想知道如何仅将name存储在嵌套在JSON对象中的商品数组中,我想将其存储到模型中。

请您花点时间考虑一下我的情况,我已经在StackOverflow和其他站点上搜索了解决方案,但它们提供的循环无法正常工作。希望我可以通过发布自己来找到答案

带有嵌套数组的JSON对象:

"jobs": [
    {
        "id": 103080,
        "user_id": 496,
        "tracker_jobs_id": 91068,
        "game_id": 1,
        "pickup_city_id": 72,
        "destination_city_id": 128,
        "cargo_id": 366,
        "pickup_company_id": 16,
        "destination_company_id": 18,
        "date": "2018-11-03",
        "distance_driven": 244,
        "load_damage": 7,
        "estimated_income": 10956,
        "total_income": 10956,
        "cargo_weight": 24,
        "division_load": 0,
        "promotional_delivery_id": null,
        "another_driver": 0,
        "division_id": null,
        "convoy_code": null,
        "comments": null,
        "created_at": "2018-11-04 00:24:42",
        "updated_at": "2018-11-04 00:24:42",
        "delete": "false",
        "status": null,
        "cargo": {
            "id": 366,
            "name": "Square Tubing",
            "price_coef": 1,
            "fragility": 0.2,
            "wotr_only": 0,
            "overweight_dlc": 0
        },
        .... (THEN IT LOOPS WITH THE NEXT JOB)

我的工作模式:

public Job (int id, int user_id, int tracker_jobs_id, int game_id, int pickup_city_id, int destination_city_id,
           int cargo_id, int pickup_company_id, int destination_company_id, Date date, int distance_driven, int load_damage,
           int estimated_income, int total_income, int cargo_weight, int division_load, int promotional_devlivery_id, int another_driver,
           int division_id, String convoy_code, String comments, String delete, String status, JSONArray cargo) {

    this.id = id;
    this.user_id = user_id;
    this.tracker_jobs_id = tracker_jobs_id;
    this.game_id = game_id;
    this.pickup_city_id = pickup_city_id;
    this.destination_city_id = destination_city_id;
    this.cargo_id = cargo_id;
    this.pickup_company_id = pickup_company_id;
    this.destination_company_id = destination_company_id;
    this.date = date;
    this.distance_driven = distance_driven;
    this.load_damage = load_damage;
    this.estimated_income = estimated_income;
    this.total_income = total_income;
    this.cargo_weight = cargo_weight;
    this.division_load = division_load;
    this.promotional_devlivery_id = promotional_devlivery_id;
    this.another_driver = another_driver;
    this.division_id = division_id;
    this.convoy_code = convoy_code;
    this.comments = comments;
    this.delete = delete;
    this.status =  status;
    this.cargo = cargo;

}

如您所见,我已经尝试过将其存储为JSONArray,但最终却只是空白[]

我如何根据请求存储它:

JSONObject jObj = new JSONObject(response);
JSONArray listJobs = jObj.getJSONArray("jobs");
Gson gson = new Gson();
sUserJobs = new ArrayList<>();
for (int i = 0; i < listJobs.length(); i++) {
     try {
          Job job = gson.fromJson(listJobs.getJSONObject(i).toString(), Job.class);
          sUserJobs.add(job);
      } catch (JSONException e) {
                  e.printStackTrace();
      }
 }

3 个答案:

答案 0 :(得分:0)

您还需要参加货运课程。然后,您需要像下面一样提取货物,同时使Job类将一组货物对象也设置为相关对象。

Cargo cargo = gson.fromJson(listJobs.getJSONObject(i).getString("cargo").toString(), cargo.class);

答案 1 :(得分:0)

您可以使用Custom Deserialization完成任务。

首先编写一个JobJsonDeserializer类,该类将从给定的json解析为您的Job模型

public class JobJsonDeserializer implements JsonDeserializer<Job> {
    @Override
    public Job deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();

        // Parse date by given format "yyyy-MM-dd"
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(jsonObject.get("date").getAsString());
        } catch (ParseException e) {
            // Do nothing
        }

        // Parse cargo json object to json array which only contains name json key.
        JSONArray cargo = new JSONArray();
        cargo.put(jsonObject.getAsJsonObject("cargo").get("name").getAsString());

        // Parse each json key to your Job model properties.
        return new Job(jsonObject.get("id").getAsInt(),
                jsonObject.get("user_id").getAsInt(),
                jsonObject.get("tracker_jobs_id").getAsInt(),
                jsonObject.get("game_id").getAsInt(),
                jsonObject.get("pickup_city_id").getAsInt(),
                jsonObject.get("destination_city_id").getAsInt(),
                jsonObject.get("cargo_id").getAsInt(),
                jsonObject.get("pickup_company_id").getAsInt(),
                jsonObject.get("destination_company_id").getAsInt(),
                date,
                jsonObject.get("distance_driven").getAsInt(),
                jsonObject.get("load_damage").getAsInt(),
                jsonObject.get("estimated_income").getAsInt(),
                jsonObject.get("total_income").getAsInt(),
                jsonObject.get("cargo_weight").getAsInt(),
                jsonObject.get("division_load").getAsInt(),
                getJsonNullableInt(jsonObject.get("promotional_delivery_id")),
                jsonObject.get("another_driver").getAsInt(),
                getJsonNullableInt(jsonObject.get("division_id")),
                getJsonNullableString(jsonObject.get("convoy_code")),
                getJsonNullableString(jsonObject.get("comments")),
                jsonObject.get("delete").getAsString(),
                getJsonNullableString(jsonObject.get("status")),
                cargo);
    }

    private int getJsonNullableInt(JsonElement jsonElement) {
        if (jsonElement.isJsonNull()) {
            return 0; // Default value for int type
        }
        return jsonElement.getAsInt();
    }

    private String getJsonNullableString(JsonElement jsonElement) {
        if (jsonElement.isJsonNull()) {
            return ""; // Default value for String type
        }
        return jsonElement.getAsString();
    }
}

然后在您的代码中使用它

JSONObject jObj = new JSONObject(response);
JSONArray listJobs = jObj.getJSONArray("jobs");

// Register a new class for deserialize a given json to your Job model.
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Job.class, new JobJsonDeserializer());
Gson customGson = gsonBuilder.create();

sUserJobs = new ArrayList<>();
for (int i = 0; i < listJobs.length(); i++) {
    try {
        Job job = customGson.fromJson(listJobs.getJSONObject(i).toString(), Job.class);
        sUserJobs.add(job);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

答案 2 :(得分:0)

更改您的工作模式:

public class Job {

    @SerializedName("id") // variable name from server
    int id = 0;
    @SerializedName("user_id")
    int user_id = 0;
    @SerializedName("tracker_jobs_id")
    int tracker_jobs_id = 0;
    @SerializedName("game_id")
    int game_id = 0;
    @SerializedName("pickup_city_id")
    int pickup_city_id = 0;
    @SerializedName("destination_city_id")
    int destination_city_id = 0;
    @SerializedName("cargo_id")
    int cargo_id = 0;
    @SerializedName("pickup_company_id")
    int pickup_company_id = 0;
    @SerializedName("destination_company_id")
    int destination_company_id = 0;
    @SerializedName("date")
    String date = "";
    @SerializedName("distance_driven")
    int distance_driven = 0;
    @SerializedName("load_damage")
    int load_damage = 0;
    @SerializedName("estimated_income")
    int estimated_income = 0;
    @SerializedName("total_income")
    int total_income = 0;
    @SerializedName("cargo_weight")
    int cargo_weight = 0;
    @SerializedName("division_load")
    int division_load = 0;
    @SerializedName("promotional_devlivery_id")
    int promotional_devlivery_id = 0;
    @SerializedName("another_driver")
    int another_driver = 0;
    @SerializedName("division_id")
    int division_id = 0;
    @SerializedName("convoy_code")
    String convoy_code = "";
    @SerializedName("comments")
    String comments = "";
    @SerializedName("delete")
    String delete = "";
    @SerializedName("status")
    String status = "";
    @SerializedName("cargo")
    Cargo cargo = new Cargo();

    public Job (int id, int user_id, int tracker_jobs_id, int game_id, int pickup_city_id, int destination_city_id,
                int cargo_id, int pickup_company_id, int destination_company_id, String date, int distance_driven, int load_damage,
                int estimated_income, int total_income, int cargo_weight, int division_load, int promotional_devlivery_id, int another_driver,
                int division_id, String convoy_code, String comments, String delete, String status, Cargo cargo) {

        this.id = id;
        this.user_id = user_id;
        this.tracker_jobs_id = tracker_jobs_id;
        this.game_id = game_id;
        this.pickup_city_id = pickup_city_id;
        this.destination_city_id = destination_city_id;
        this.cargo_id = cargo_id;
        this.pickup_company_id = pickup_company_id;
        this.destination_company_id = destination_company_id;
        this.date = date;
        this.distance_driven = distance_driven;
        this.load_damage = load_damage;
        this.estimated_income = estimated_income;
        this.total_income = total_income;
        this.cargo_weight = cargo_weight;
        this.division_load = division_load;
        this.promotional_devlivery_id = promotional_devlivery_id;
        this.another_driver = another_driver;
        this.division_id = division_id;
        this.convoy_code = convoy_code;
        this.comments = comments;
        this.delete = delete;
        this.status =  status;
        this.cargo = cargo;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getUser_id() {
        return user_id;
    }

    public void setUser_id(int user_id) {
        this.user_id = user_id;
    }

    public int getTracker_jobs_id() {
        return tracker_jobs_id;
    }

    public void setTracker_jobs_id(int tracker_jobs_id) {
        this.tracker_jobs_id = tracker_jobs_id;
    }

    public int getGame_id() {
        return game_id;
    }

    public void setGame_id(int game_id) {
        this.game_id = game_id;
    }

    public int getPickup_city_id() {
        return pickup_city_id;
    }

    public void setPickup_city_id(int pickup_city_id) {
        this.pickup_city_id = pickup_city_id;
    }

    public int getDestination_city_id() {
        return destination_city_id;
    }

    public void setDestination_city_id(int destination_city_id) {
        this.destination_city_id = destination_city_id;
    }

    public int getCargo_id() {
        return cargo_id;
    }

    public void setCargo_id(int cargo_id) {
        this.cargo_id = cargo_id;
    }

    public int getPickup_company_id() {
        return pickup_company_id;
    }

    public void setPickup_company_id(int pickup_company_id) {
        this.pickup_company_id = pickup_company_id;
    }

    public int getDestination_company_id() {
        return destination_company_id;
    }

    public void setDestination_company_id(int destination_company_id) {
        this.destination_company_id = destination_company_id;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public int getDistance_driven() {
        return distance_driven;
    }

    public void setDistance_driven(int distance_driven) {
        this.distance_driven = distance_driven;
    }

    public int getLoad_damage() {
        return load_damage;
    }

    public void setLoad_damage(int load_damage) {
        this.load_damage = load_damage;
    }

    public int getEstimated_income() {
        return estimated_income;
    }

    public void setEstimated_income(int estimated_income) {
        this.estimated_income = estimated_income;
    }

    public int getTotal_income() {
        return total_income;
    }

    public void setTotal_income(int total_income) {
        this.total_income = total_income;
    }

    public int getCargo_weight() {
        return cargo_weight;
    }

    public void setCargo_weight(int cargo_weight) {
        this.cargo_weight = cargo_weight;
    }

    public int getDivision_load() {
        return division_load;
    }

    public void setDivision_load(int division_load) {
        this.division_load = division_load;
    }

    public int getPromotional_devlivery_id() {
        return promotional_devlivery_id;
    }

    public void setPromotional_devlivery_id(int promotional_devlivery_id) {
        this.promotional_devlivery_id = promotional_devlivery_id;
    }

    public int getAnother_driver() {
        return another_driver;
    }

    public void setAnother_driver(int another_driver) {
        this.another_driver = another_driver;
    }

    public int getDivision_id() {
        return division_id;
    }

    public void setDivision_id(int division_id) {
        this.division_id = division_id;
    }

    public String getConvoy_code() {
        return convoy_code;
    }

    public void setConvoy_code(String convoy_code) {
        this.convoy_code = convoy_code;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getDelete() {
        return delete;
    }

    public void setDelete(String delete) {
        this.delete = delete;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public List<Cargo> getCargo() {
        return cargo;
    }

    public void setCargo(List<Cargo> cargo) {
        this.cargo = cargo;
    }
}

并创建名为“货运”的新类

public class Cargo {

    @SerializedName("id")
    int id = 0;
    @SerializedName("name")
    String name = "";
    @SerializedName("price_coef")
    int price_coef = 0;
    @SerializedName("fragility")
    double fragility = 0.0;
    @SerializedName("wotr_only")
    int wotr_only = 0;
    @SerializedName("overweight_dlc")
    int overweight_dlc = 0;

    public Cargo () {
    }

    public Cargo (int id, String name, int price_coef, double fragility, int wotr_only, int overweight_dlc) {
        this.id = id;
        this.name = name;
        this.price_coef = price_coef;
        this.fragility = fragility;
        this.wotr_only = wotr_only;
        this.overweight_dlc = overweight_dlc;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public int getPrice_coef() {
        return price_coef;
    }

    public void setPrice_coef(int price_coef) {
        this.price_coef = price_coef;
    }

    public double getFragility() {
        return fragility;
    }

    public void setFragility(double fragility) {
        this.fragility = fragility;
    }

    public int getWotr_only() {
        return wotr_only;
    }

    public void setWotr_only(int wotr_only) {
        this.wotr_only = wotr_only;
    }

    public int getOverweight_dlc() {
        return overweight_dlc;
    }

    public void setOverweight_dlc(int overweight_dlc) {
        this.overweight_dlc = overweight_dlc;
    }
}

或..您可以将json发布到此站点并下载模型:

http://www.jsonschema2pojo.org/

目标语言:Java

源类型:JSON模式或JSON

注释样式:Gson