如何将JSONobject转换为JSonArray ......?

时间:2017-08-01 06:28:48

标签: android arrays

我有回复

{

"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?

3 个答案:

答案 0 :(得分:3)

您应该使用 ITERATOR

  

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

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

答案 1 :(得分:1)

  1. 将对象转换为字符串
  2. 将First {更改为[和last} to]
  3. 将字符串转换为JSONArray
  4. 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)
            {
    
            }
    

答案 2 :(得分:1)

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");