【问题标题】:how to convert JSONobject to JSonArray......?如何将 JSONobject 转换为 JSONArray……?
【发布时间】:2018-01-07 21:13:57
【问题描述】:

我有回应

{

"p1":{
"date":"Sat, 29 Jul 2017 03:31:43 GMT",
"plan_id":"5c4c6548-38cb-4dbb-b7a3-a3f260fb8532",
"plan_name":"Ultra50",
"pulse":1,
"tarrif":1,
"validity":30
},
"p2":{
"date":"Sat, 29 Jul 2017 03:31:43 GMT",
"plan_id":"5c4c6548-38cb-4dbb-b7a3-a3f260fb8532",
"plan_name":"Ultra50",
"pulse":1,
"tarrif":1,
"validity":30
}
}

这是我的代码

 Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {

                JSONObject plan=response.getJSONObject("p1");
                Iterator x=plan.keys();
                JSONArray jsonElements=new JSONArray();
                while (x.hasNext()){
                    String key=(String) x.next();
                    jsonElements.put(plan.get(key));
                    Log.e(TAG, "onResponse: "+key );

                }
                Log.d(TAG, "onResponse: "+jsonElements.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }

如何在一个 JsonArray 中转换 p1,p2,p3?

【问题讨论】:

  • 你的问题不清楚。
  • 我想在 listview 中的这个 Json 响应...有可能吗? @IntelliJAmiya
  • 是的。为什么不..
  • 如何告诉我我想在列表中显示 p1,p2,p3 对象值...@IntelliJAmiya
  • 检查我的答案。

标签: android arrays


【解决方案1】:
  1. 将对象转换为字符串
  2. 将 First { 替换为 [ 并将最后一个 } 替换为 ]​​i>
  3. 将字符串转换为 JSONArray
String res = response.toString().trim();
        res = res.replaceFirst("\{","]");
        res = res.substring(0,res.length()-1) + "]";
        try {
                   JSONArray arr = new JSONArray(res.toString());
        }catch (JSONException j)
        {

        }

【讨论】:

  • 我知道,但我无法更改响应。请在 Android 代码中给我一个解决方案...
【解决方案2】:
Iterator planKeys = response.keys();
{
    JSONArray jsonElements=new JSONArray();
    while(planKeys.hasNext()){
        String key = (String) planKeys.next();
        JSONObject plan = response.getJSONObject(key);
        Iterator x=plan.keys();
        while (x.hasNext()){
            String key=(String) x.next();
            jsonElements.put(plan.get(key));
            Log.e(TAG, "onResponse: "+key );

        }
    }
}

JSONObject plan=response.getJSONObject("p1");

【讨论】:

  • 为什么是JSONArray ??
  • 因为你在你的问题中写了你想要 JSONArray
  • 创建一个模型类和 ArrayList 并将你的 jsonarray 添加到列表中
【解决方案3】:

您应该使用 ITERATOR

用于逐一遍历集合对象元素。

 Iterator  iteratorObj = response.keys();
        while (iteratorObj.hasNext())
        {
            String getKEY = (String)iteratorObj.next();
            System.out.println("Key: " + Key + "------>" + getKEY); // p1,p2
        }

【讨论】:

    猜你喜欢
    • 2011-11-03
    • 2016-06-05
    • 2013-06-27
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多