Moshi + Retrofit - Обработка JSON Ответ - PullRequest
0 голосов
/ 29 января 2020

Как отобразить ответ json в XML,

Я получаю ответ json для response.body (). ToString (), как и ожидалось. Я не уверен, как получить значение из JSON.

Но я не уверен, как перебирать значения json.

{
    "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"
            }
        }
    ]
}

Я использовал http://www.jsonschema2pojo.org/ для преобразования json

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

ClassName - OrderDetailsResponse

Target language:
Java 

Source type:
JSON

Annotation style: Moshi 

---------- ------------------------- пакет 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();
}

}

------ ----------------------------- пакет 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();
}

}

- --------------------------------- пакет 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();
}

}

----------------------------------- пакет 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();
    }
}

1 Ответ

1 голос
/ 29 января 2020

Вам не нужно перебирать JSON, так как вы уже создали классы POJO для вашего JSON, и вы получаете его в onResponse с response.body(). Таким образом, вы можете просто использовать его для итерации ваших данных.

Например, предположим, что вам нужен create_at из table1, вы можете получить к нему доступ как:

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