简体   繁体   中英

Moshi + Retrofit - Handling JSON Response

How do I display the json response in the XML,

I am getting the json response for response.body().toString() as expected. I am not sure how do get the value from the JSON.

But I am not sure how do I iterate through the json values.

{
    "data": [
        {
            "id": 4,
            "customer_id": 1,
            "order_name" : "Order Details",
            "created_at": "2020-01-04 14:18:30",
            "table1": {
                "id": 1,
                "customer_id": 1,
                "order_details_name": "Product Name",
                "description": null,
                "status": 1,
                "deleted_at": null,
                "created_at": "2020-01-04 08:03:45",
                "updated_at": "2020-01-04 08:54:23"
            },
            "table2": {
                "id": 1,
                "customer_id": 1,
                "order_information": "Order Details",
                "description": "desc",
                "status": 1,
                "deleted_at": null,
                "created_at": "2020-01-04 08:28:04",
                "updated_at": "2020-01-04 08:57:17"
            }
        }
    ]
}

I was using the http://www.jsonschema2pojo.org/ to convert the json

package - package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;

ClassName - OrderDetailsResponse

Target language:
Java 

Source type:
JSON

Annotation style: Moshi 

-----------------------------------package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;.Datum.java-----------------------------------

package package com.tesmachino.saycure.entities.OrderHistory.OrderDetail; ;

import com.squareup.moshi.Json;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Datum {

@Json(name = "id")
private Integer id;
@Json(name = "customer_id")
private Integer customerId;
@Json(name = "order_name")
private String orderName;
@Json(name = "created_at")
private String createdAt;
@Json(name = "table1")
private Table1 table1;
@Json(name = "table2")
private Table2 table2;

public Integer getId() {
return id;
}

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

public Integer getCustomerId() {
return customerId;
}

public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}

public String getOrderName() {
return orderName;
}

public void setOrderName(String orderName) {
this.orderName = orderName;
}

public String getCreatedAt() {
return createdAt;
}

public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}

public Table1 getTable1() {
return table1;
}

public void setTable1(Table1 table1) {
this.table1 = table1;
}

public Table2 getTable2() {
return table2;
}

public void setTable2(Table2 table2) {
this.table2 = table2;
}

@Override
public String toString() {
return new ToStringBuilder(this).append("id", id).append("customerId", customerId).append("orderName", orderName).append("createdAt", createdAt).append("table1", table1).append("table2", table2).toString();
}

}

-----------------------------------package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;.OrderDetailsResponse.java-----------------------------------

package package com.tesmachino.saycure.entities.OrderHistory.OrderDetail; ;

import java.util.List;
import com.squareup.moshi.Json;
import org.apache.commons.lang.builder.ToStringBuilder;

public class OrderDetailsResponse {

@Json(name = "data")
private List<Datum> data = null;

public List<Datum> getData() {
return data;
}

public void setData(List<Datum> data) {
this.data = data;
}

@Override
public String toString() {
return new ToStringBuilder(this).append("data", data).toString();
}

}

-----------------------------------package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;.Table1.java-----------------------------------

package package com.tesmachino.saycure.entities.OrderHistory.OrderDetail; ;

import com.squareup.moshi.Json;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Table1 {

@Json(name = "id")
private Integer id;
@Json(name = "customer_id")
private Integer customerId;
@Json(name = "order_details_name")
private String orderDetailsName;
@Json(name = "description")
private Object description;
@Json(name = "status")
private Integer status;
@Json(name = "deleted_at")
private Object deletedAt;
@Json(name = "created_at")
private String createdAt;
@Json(name = "updated_at")
private String updatedAt;

public Integer getId() {
return id;
}

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

public Integer getCustomerId() {
return customerId;
}

public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}

public String getOrderDetailsName() {
return orderDetailsName;
}

public void setOrderDetailsName(String orderDetailsName) {
this.orderDetailsName = orderDetailsName;
}

public Object getDescription() {
return description;
}

public void setDescription(Object description) {
this.description = description;
}

public Integer getStatus() {
return status;
}

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

public Object getDeletedAt() {
return deletedAt;
}

public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}

public String getCreatedAt() {
return createdAt;
}

public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}

public String getUpdatedAt() {
return updatedAt;
}

public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}

@Override
public String toString() {
return new ToStringBuilder(this).append("id", id).append("customerId", customerId).append("orderDetailsName", orderDetailsName).append("description", description).append("status", status).append("deletedAt", deletedAt).append("createdAt", createdAt).append("updatedAt", updatedAt).toString();
}

}

-----------------------------------package com.tesmachino.saycure.entities.OrderHistory.OrderDetail;.Table2.java-----------------------------------

package package com.tesmachino.saycure.entities.OrderHistory.OrderDetail; ;

import com.squareup.moshi.Json;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Table2 {

@Json(name = "id")
private Integer id;
@Json(name = "customer_id")
private Integer customerId;
@Json(name = "order_information")
private String orderInformation;
@Json(name = "description")
private String description;
@Json(name = "status")
private Integer status;
@Json(name = "deleted_at")
private Object deletedAt;
@Json(name = "created_at")
private String createdAt;
@Json(name = "updated_at")
private String updatedAt;

public Integer getId() {
return id;
}

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

public Integer getCustomerId() {
return customerId;
}

public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}

public String getOrderInformation() {
return orderInformation;
}

public void setOrderInformation(String orderInformation) {
this.orderInformation = orderInformation;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Integer getStatus() {
return status;
}

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

public Object getDeletedAt() {
return deletedAt;
}

public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}

public String getCreatedAt() {
return createdAt;
}

public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}

public String getUpdatedAt() {
return updatedAt;
}

public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}

@Override
public String toString() {
return new ToStringBuilder(this).append("id", id).append("customerId", customerId).append("orderInformation", orderInformation).append("description", description).append("status", status).append("deletedAt", deletedAt).append("createdAt", createdAt).append("updatedAt", updatedAt).toString();
}

}

OrderDetail

package com.tesmachino.saycure;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.tesmachino.saycure.Auth.TokenManager;
import com.tesmachino.saycure.entities.OrderHistory.OrderDetail.OrderDetailsResponse;
import com.tesmachino.saycure.entities.OrderHistory.OrderHistoryResponse;
import com.tesmachino.saycure.entities.UserDetails.UserDetailsGetResponse;
import com.tesmachino.saycure.network.ApiService;
import com.tesmachino.saycure.network.RetrofitBuilder;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrderDetail extends AppCompatActivity {

    ApiService service;
    TokenManager tokenManager;

    Call<OrderDetailsResponse> call;


    private static final String TAG = "OrderDetail";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);

        ButterKnife.bind(this);

        tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
        service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
    }


    @Override
    protected void onResume() {

        //Get the Data from the Intent
        if (getIntent().hasExtra("order_id")) {
            int order_id = getIntent().getIntExtra("order_id", 1);
            Log.d(TAG, "IntentWorking" + order_id);

            call = service.orderDetails(order_id);

            call.enqueue(new Callback<OrderDetailsResponse>() {
                @Override
                public void onResponse(Call<OrderDetailsResponse> call, Response<OrderDetailsResponse> response) {
                    OrderDetailsResponse orderDetails = response.body();

                    if (orderDetails != null){

                    }
                    Toast.makeText(OrderDetail.this, "" + response.body().toString(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Call<OrderDetailsResponse> call, Throwable t) {
                    Log.w(TAG, "onFailure: " + t.getMessage());
                    Toast.makeText(OrderDetail.this, "Failure" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

        } else {

            Toast.makeText(this, "There seems to be an error while fetching the Order Id. Please Try Again", Toast.LENGTH_SHORT).show();
        }

        super.onResume();
    }
}

You do not have to iterate through JSON as you already have made POJO classes for your JSON, and you are getting it in onResponse with response.body() . So you can just use it to iterate through your data.

For example, suppose you need created_at from table1 , you can access it like:

String createdAt = orderDetails.getData().get(0).getTable1().getCreatedAt()

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