【问题标题】:How to convert the given json to json array如何将给定的json转换为json数组
【发布时间】:2017-09-05 08:23:36
【问题描述】:

我要将 json 数据转换为 json 数组,但我得到的错误是:- type org.json。 JSONObject 无法转换为 JSONArray。如何解决这个问题。 Click here view the json data private void populateDashBoardReport(Bundle bundle) {

    if (getContext() != null && bundle != null && bundle.getLong("TenantId") != 0L) {

        isDataLoaded = true; // indicate that the data was loaded already

        mTenantId = bundle.getLong("TenantId");
        boolean isTenant = bundle.getBoolean("IsTenant");
        long userId = (isTenant ? 0 : bundle.getLong("UserId"));

        String url = CashPunditUtils.BaseUrl + "/GetDashBoard?TenantId=" + mTenantId + "&AppUserId=" + userId;
        final ProgressDialog progressDialog;

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            progressDialog = new ProgressDialog(getContext(), android.support.v7.appcompat.R.style.Theme_AppCompat_Light_Dialog_Alert);
        } else {
            progressDialog = new ProgressDialog(getContext());
        }

        progressDialog.setMessage("Loading...");
        progressDialog.show();

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                progressDialog.dismiss();

                mDashBoardVOsList = parseJsonResponse(response);

                // set adapter for recycler view
                mRecyclerViewAdapter = new MyRecyclerViewAdapter(mDashBoardVOsList);
                mRecyclerView.setAdapter(mRecyclerViewAdapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                progressDialog.dismiss();

                Log.e(TAG, "Error occured on DashBoard request :" + error.getMessage());

                Toast.makeText(getContext(), "Error loading DashBoard report :" + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        // Change the timeout to 1 minute
        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        // Adding request to volley request queue
        VolleySingleton.getInstance(getContext()).addToRequestQueue(jsonArrayRequest);
    }
}

私有列表 parseJsonResponse(JSONArray 响应) {

    List<DashBoardVO> dashboardVOsList = null;

    if (response != null) {

        dashboardVOsList = new ArrayList<>();

        for (int index = 0; index < response.length(); index++) {

            DashBoardVO dashBoardVO = new DashBoardVO();

            try {
                JSONObject jsonObject = response.getJSONObject(index);

                dashBoardVO.setReceivable(jsonObject.getDouble("Receivable"));
                dashBoardVO.setPayable(jsonObject.getDouble("Payable"));

                dashboardVOsList.add(dashBoardVO);

            } catch (JSONException e) {
                Log.e(TAG, "Error occured while parsing JSON :" + e.getMessage());
            }
        }
    }
    return dashboardVOsList;
}

【问题讨论】:

  • 我添加了将值设置为模型的代码

标签: android arrays json android-layout android-fragments


【解决方案1】:

将您的请求更改为 JsonObjectRequest

 JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                progressDialog.dismiss();

                mDashBoardVOsList = parseJsonResponse(response);

                // set adapter for recycler view
                mRecyclerViewAdapter = new MyRecyclerViewAdapter(mDashBoardVOsList);
                mRecyclerView.setAdapter(mRecyclerViewAdapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                progressDialog.dismiss();

                Log.e(TAG, "Error occured on DashBoard request :" + error.getMessage());

                Toast.makeText(getContext(), "Error loading DashBoard report :" + error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

还有把json解析改成这个

 private List parseJsonResponse(JSONObject response) {

    List<DashBoardVO> dashboardVOsList = null;

    if (response != null) {
        JSONArray array=response.getJSONArray("lstGraph");
        dashboardVOsList = new ArrayList<>();

        for (int index = 0; index < array.length(); index++) {

            DashBoardVO dashBoardVO = new DashBoardVO();

            try {
                JSONObject jsonObject = array.getJSONObject(index);

                dashBoardVO.setReceivable(jsonObject.getDouble("Receivable"));
                dashBoardVO.setPayable(jsonObject.getDouble("Payable"));

                dashboardVOsList.add(dashBoardVO);

            } catch (JSONException e) {
                Log.e(TAG, "Error occured while parsing JSON :" + e.getMessage());
            }
        }
    }
    return dashboardVOsList;
}

更新:

您可以使用 Gson 库将 JSON 转换为 Java Pojo 类。

在你的 build.gradle 中添加 gson 依赖

compile 'com.google.code.gson:gson:2.8.1'

添加以下模型

 -----------------------------------com.example.DashboardVOsList.java-----------------------------------

package com.example;

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

public class DashboardVOsList {

@SerializedName("Receivable")
@Expose
private Double receivable;
@SerializedName("Payable")
@Expose
private Double payable;
@SerializedName("oPendingFollowup")
@Expose
private OPendingFollowup oPendingFollowup;
@SerializedName("oPDCReceive")
@Expose
private OPDCReceive oPDCReceive;
@SerializedName("oInvOverdue")
@Expose
private OInvOverdue oInvOverdue;
@SerializedName("oInvAlmostOverdue")
@Expose
private OInvAlmostOverdue oInvAlmostOverdue;
@SerializedName("lstGraph")
@Expose
private List<LstGraph> lstGraph = null;

public Double getReceivable() {
return receivable;
}

public void setReceivable(Double receivable) {
this.receivable = receivable;
}

public Double getPayable() {
return payable;
}

public void setPayable(Double payable) {
this.payable = payable;
}

public OPendingFollowup getOPendingFollowup() {
return oPendingFollowup;
}

public void setOPendingFollowup(OPendingFollowup oPendingFollowup) {
this.oPendingFollowup = oPendingFollowup;
}

public OPDCReceive getOPDCReceive() {
return oPDCReceive;
}

public void setOPDCReceive(OPDCReceive oPDCReceive) {
this.oPDCReceive = oPDCReceive;
}

public OInvOverdue getOInvOverdue() {
return oInvOverdue;
}

public void setOInvOverdue(OInvOverdue oInvOverdue) {
this.oInvOverdue = oInvOverdue;
}

public OInvAlmostOverdue getOInvAlmostOverdue() {
return oInvAlmostOverdue;
}

public void setOInvAlmostOverdue(OInvAlmostOverdue oInvAlmostOverdue) {
this.oInvAlmostOverdue = oInvAlmostOverdue;
}

public List<LstGraph> getLstGraph() {
return lstGraph;
}

public void setLstGraph(List<LstGraph> lstGraph) {
this.lstGraph = lstGraph;
}

}
-----------------------------------com.example.LstGraph.java-----------------------------------

package com.example;

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

public class LstGraph {

@SerializedName("Receivable")
@Expose
private Double receivable;
@SerializedName("Payable")
@Expose
private Double payable;
@SerializedName("CashFlow")
@Expose
private Double cashFlow;
@SerializedName("CFDate")
@Expose
private String cFDate;

public Double getReceivable() {
return receivable;
}

public void setReceivable(Double receivable) {
this.receivable = receivable;
}

public Double getPayable() {
return payable;
}

public void setPayable(Double payable) {
this.payable = payable;
}

public Double getCashFlow() {
return cashFlow;
}

public void setCashFlow(Double cashFlow) {
this.cashFlow = cashFlow;
}

public String getCFDate() {
return cFDate;
}

public void setCFDate(String cFDate) {
this.cFDate = cFDate;
}

}
-----------------------------------com.example.OInvAlmostOverdue.java-----------------------------------

package com.example;

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

public class OInvAlmostOverdue {

@SerializedName("Customers")
@Expose
private Integer customers;
@SerializedName("Invoices")
@Expose
private Integer invoices;
@SerializedName("PerRec")
@Expose
private Double perRec;
@SerializedName("InvValue")
@Expose
private Double invValue;

public Integer getCustomers() {
return customers;
}

public void setCustomers(Integer customers) {
this.customers = customers;
}

public Integer getInvoices() {
return invoices;
}

public void setInvoices(Integer invoices) {
this.invoices = invoices;
}

public Double getPerRec() {
return perRec;
}

public void setPerRec(Double perRec) {
this.perRec = perRec;
}

public Double getInvValue() {
return invValue;
}

public void setInvValue(Double invValue) {
this.invValue = invValue;
}

}
-----------------------------------com.example.OInvOverdue.java-----------------------------------

package com.example;

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

public class OInvOverdue {

@SerializedName("Customers")
@Expose
private Integer customers;
@SerializedName("Invoices")
@Expose
private Integer invoices;
@SerializedName("InvValue")
@Expose
private Double invValue;
@SerializedName("YetToFollow")
@Expose
private Integer yetToFollow;

public Integer getCustomers() {
return customers;
}

public void setCustomers(Integer customers) {
this.customers = customers;
}

public Integer getInvoices() {
return invoices;
}

public void setInvoices(Integer invoices) {
this.invoices = invoices;
}

public Double getInvValue() {
return invValue;
}

public void setInvValue(Double invValue) {
this.invValue = invValue;
}

public Integer getYetToFollow() {
return yetToFollow;
}

public void setYetToFollow(Integer yetToFollow) {
this.yetToFollow = yetToFollow;
}

}
-----------------------------------com.example.OPDCReceive.java-----------------------------------

package com.example;

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

public class OPDCReceive {

@SerializedName("Customers")
@Expose
private Integer customers;
@SerializedName("PDCs")
@Expose
private Integer pDCs;
@SerializedName("UpTo7Days")
@Expose
private String upTo7Days;
@SerializedName("PDCValue")
@Expose
private Double pDCValue;

public Integer getCustomers() {
return customers;
}

public void setCustomers(Integer customers) {
this.customers = customers;
}

public Integer getPDCs() {
return pDCs;
}

public void setPDCs(Integer pDCs) {
this.pDCs = pDCs;
}

public String getUpTo7Days() {
return upTo7Days;
}

public void setUpTo7Days(String upTo7Days) {
this.upTo7Days = upTo7Days;
}

public Double getPDCValue() {
return pDCValue;
}

public void setPDCValue(Double pDCValue) {
this.pDCValue = pDCValue;
}

}
-----------------------------------com.example.OPendingFollowup.java-----------------------------------

package com.example;

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

public class OPendingFollowup {

@SerializedName("Customers")
@Expose
private Integer customers;
@SerializedName("Invoices")
@Expose
private Integer invoices;
@SerializedName("PerRec")
@Expose
private Double perRec;
@SerializedName("InvValue")
@Expose
private Double invValue;

public Integer getCustomers() {
return customers;
}

public void setCustomers(Integer customers) {
this.customers = customers;
}

public Integer getInvoices() {
return invoices;
}

public void setInvoices(Integer invoices) {
this.invoices = invoices;
}

public Double getPerRec() {
return perRec;
}

public void setPerRec(Double perRec) {
this.perRec = perRec;
}

public Double getInvValue() {
return invValue;
}

public void setInvValue(Double invValue) {
this.invValue = invValue;
}

}

将 json 转换为 java pojo 使用下面的代码

     private  DashboardVOsList parseJsonResponse(JSONObject response) {



    Gson gson =new Gson(); 
    DashboardVOsList dashboardVOsList= gson.fromJson(response.toString(),DashboardVOsList.class);
return dashboardVOsList


}

您可以使用http://www.jsonschema2pojo.org/ 来创建模型

【讨论】:

  • JSONObject jsonObject = response.getJSONObject(index);我在这一行索引中收到错误。错误是:Json 对象不能应用于 int
  • 我还需要所有字段,不仅是 lstGraph。
  • 您可以迭代每个字段以获取该值。或者你可以使用 Gson 进行 Json 序列化。我会更新我的代码
  • 何。谢谢@VInayak,我会检查的。
  • 我编辑了我的答案。将您的 json 响应粘贴到 jsonschema2pojo.org 以创建模型
【解决方案2】:

org.json。 JSONObject 无法转换为 JSONArray

你应该调用 JSONObject 而不是 JSONArray

不要

   public void onResponse(JSONArray  response) {

   public void onResponse(JSONObject response) {

你的 JSON

{"Receivable":1967560.60,"Payable":7508676.00,"oPendingFollowup":{"Customers":5,"Invoices":7,"PerRec":509.62,"InvValue":10027000.00},"oPDCReceive":

private List parseJsonResponse(JSONObject response) 
{

    List<DashBoardVO> dashboardVOsList = null;
    if (response != null) 
    {
        dashboardVOsList = new ArrayList<>();
        DashBoardVO dashBoardVO = new DashBoardVO();

             for (int index = 0; index < response.length(); index++) 
               {

                dashBoardVO.setReceivable(response.getDouble("Receivable"));
                dashBoardVO.setPayable(response.getDouble("Payable"));
                dashboardVOsList.add(dashBoardVO);
                }


    }
        return dashboardVOsList;
}

【讨论】:

  • 在响应中找到错误。错误是:无法应用 mDashBoardVOsList = parseJsonResponse(response);
  • @RakeshKadadhi 你的responseJSONObject
  • @RakeshKadadhi 遇到同样的问题了吗?
  • (response.getDouble("Receivable"));在这一行 unhanded exception json 中找到错误
  • @RakeshKadadhi 添加try catch 块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
相关资源
最近更新 更多