简体   繁体   中英

How to create pojo class of Object of ArrayList from REST API response?

I'm working on project in which I have to implement on API. This API repsonse is objects of ArrayList. Can you please help me with creating its POJO class and if possible its implementation. I'm using retrofit2 & GSON.

As shown in following JSON schema, brand names will be added in brandsonly by admin, and it will be added in allorders as a arraylist which have multiple sub-objects.

Like, if admin add Redmi in the brandsonly then it will create Redmi[] in the allorders

{
    "status": "success",
    "brandsonly": [
        {
            "_id": "",
            "brandname": "SAMSUNG",
        },
        {
            "_id": "",
            "brandname": "VIVO",
        },
        {
            "_id": "",
            "brandname": "NOKIA"
        },
        {
            "_id": "",
            "brandname": "IPHONE",
        }
    ],
    "allorders": {
        "SAMSUNG": [],
        "VIVO": [],
        "NOKIA": [],
        "IPHONE": [
            {
                "_id": "",
                "order_id": "",
                "__v": 0,
                "adminconfirmation": 1,
                "finalpricetodeduct": 30950
            },
            {
                "_id": "",
                "order_id": "",
                "__v": 0,
                "adminconfirmation": 1,
                "finalpricetodeduct": 
            }
        ]
    },
}

My Retrofit call from activity:

        final AllOrdersResponse allOrdersResponse = new AllOrdersResponse(userID);
        Call<AllOrdersResponse> responseCall = retrofit_interface.allOrderResponse(allOrdersResponse, "Bearer " + AuthToken);

        responseCall.enqueue(new Callback<AllOrdersResponse>() {
            @Override
            public void onResponse(@NotNull Call<AllOrdersResponse> call, @NotNull Response<AllOrdersResponse> response) {
                AllOrdersResponse response1 = response.body();
            
            }

            @Override
            public void onFailure(@NotNull Call<AllOrdersResponse> call, @NotNull Throwable t) {
                if (t instanceof SocketTimeoutException)
                    Toast.makeText(context, "Socket Time out. Please try again.", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(context, t.toString(), Toast.LENGTH_LONG).show();
            }
        });

I dont think a POJO schema would work in this instance as it will always change. It would be much better is the allorders was the same as brandsonly a JSON Array of JSON Array

However, if that cannot be changed have a look at the below.

    final AllOrdersResponse allOrdersResponse = new AllOrdersResponse(userID);
    Call<AllOrdersResponse> responseCall = retrofit_interface.allOrderResponse(allOrdersResponse, "Bearer " + AuthToken);

    responseCall.enqueue(new Callback<AllOrdersResponse>() {
        @Override
        public void onResponse(@NotNull Call<AllOrdersResponse> call, @NotNull Response<AllOrdersResponse> response) {
            AllOrdersResponse response1 = response.body();
            List<String> brands = new ArrayList<>();
            List<Map<String, Product>> products = new ArrayList<>();
            JSONObject jsonObject = new JSONObject(response1); 
            for(JSONObject brand : jsonObject.get("brandsonly")){
                 brands.add(brand.getvalue("brandname"));
            }

             if(brands.size= > 0){
                for(String brandname: brands){
                    HashMap<String, Product> tempHash = new HashMap<>();
                    JSONArray temp = jsonObject.getJSONArray(brandname);
                    foreach(JSONObject x : temp){
                           Product product = new Product();
                           product.FromJSONObject(x);
                           temp.put(brandname, product);
                    }
                    products.add(tempHash);
              }
           }
        }

        @Override
        public void onFailure(@NotNull Call<AllOrdersResponse> call, @NotNull Throwable t) {
            if (t instanceof SocketTimeoutException)
                Toast.makeText(context, "Socket Time out. Please try again.", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context, t.toString(), Toast.LENGTH_LONG).show();
        }
    });

So you have a list of BandNames with a value of each product.

I would also recommend looking at jsonschema2.pojo

Your JSON has some missing { and some extra , . So this is your JSON fixed:

{
    "status": "success",
    "brandsonly": [
        {
            "_id": "",
            "brandname": "SAMSUNG"
        },
        {
            "_id": "",
            "brandname": "VIVO"
        },
        {
            "_id": "",
            "brandname": "NOKIA"
        },
        {
            "_id": "",
            "brandname": "IPHONE"
        }
    ],
    "allorders": {
        "SAMSUNG": [],
        "VIVO": [],
        "NOKIA": [],
        "IPHONE": [
            {
                "_id": "",
                "order_id": "",
                "__v": 0,
                "adminconfirmation": 1,
                "finalpricetodeduct": 30950
            },
            {
                "_id": "",
                "order_id": "",
                "__v": 0,
                "adminconfirmation": 1,
                "finalpricetodeduct": 30950
            }
        ]
    }
}

And these are the Pojo classes for storing your JSON:

Allorders class:


package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Allorders {

@SerializedName("SAMSUNG")
@Expose
private List<Object> sAMSUNG = null;
@SerializedName("VIVO")
@Expose
private List<Object> vIVO = null;
@SerializedName("NOKIA")
@Expose
private List<Object> nOKIA = null;
@SerializedName("IPHONE")
@Expose
private List<IPHONE> iPHONE = null;

public List<Object> getSAMSUNG() {
return sAMSUNG;
}

public void setSAMSUNG(List<Object> sAMSUNG) {
this.sAMSUNG = sAMSUNG;
}

public List<Object> getVIVO() {
return vIVO;
}

public void setVIVO(List<Object> vIVO) {
this.vIVO = vIVO;
}

public List<Object> getNOKIA() {
return nOKIA;
}

public void setNOKIA(List<Object> nOKIA) {
this.nOKIA = nOKIA;
}

public List<IPHONE> getIPHONE() {
return iPHONE;
}

public void setIPHONE(List<IPHONE> iPHONE) {
this.iPHONE = iPHONE;
}

}

Brandsonly class:


package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Brandsonly {

@SerializedName("_id")
@Expose
private String id;
@SerializedName("brandname")
@Expose
private String brandname;

public String getId() {
return id;
}

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

public String getBrandname() {
return brandname;
}

public void setBrandname(String brandname) {
this.brandname = brandname;
}
}

IPHONE class:


package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class IPHONE {

@SerializedName("_id")
@Expose
private String id;
@SerializedName("order_id")
@Expose
private String orderId;
@SerializedName("__v")
@Expose
private Integer v;
@SerializedName("adminconfirmation")
@Expose
private Integer adminconfirmation;
@SerializedName("finalpricetodeduct")
@Expose
private Integer finalpricetodeduct;

public String getId() {
return id;
}

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

public String getOrderId() {
return orderId;
}

public void setOrderId(String orderId) {
this.orderId = orderId;
}

public Integer getV() {
return v;
}

public void setV(Integer v) {
this.v = v;
}

public Integer getAdminconfirmation() {
return adminconfirmation;
}

public void setAdminconfirmation(Integer adminconfirmation) {
this.adminconfirmation = adminconfirmation;
}

public Integer getFinalpricetodeduct() {
return finalpricetodeduct;
}

public void setFinalpricetodeduct(Integer finalpricetodeduct) {
this.finalpricetodeduct = finalpricetodeduct;
}
}

MyPojo class:



package com.example;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class MyPojo {

@SerializedName("status")
@Expose
private String status;
@SerializedName("brandsonly")
@Expose
private List<Brandsonly> brandsonly = null;
@SerializedName("allorders")
@Expose
private Allorders allorders;

public String getStatus() {
return status;
}

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

public List<Brandsonly> getBrandsonly() {
return brandsonly;
}

public void setBrandsonly(List<Brandsonly> brandsonly) {
this.brandsonly = brandsonly;
}

public Allorders getAllorders() {
return allorders;
}

public void setAllorders(Allorders allorders) {
this.allorders = allorders;
}

}

Next time you can use this handy website .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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