【问题标题】:How to convert JSONObjects to JSONArray?如何将 JSONObjects 转换为 JSONArray?
【发布时间】:2014-05-06 10:27:20
【问题描述】:

我有这样的回应:

{
 "songs":{
          "2562862600":{"id":"2562862600""pos":1},
          "2562862620":{"id":"2562862620""pos":1},
          "2562862604":{"id":"2562862604""pos":1},
          "2573433638":{"id":"2573433638""pos":1}
         }
 }

这是我的代码:

List<NameValuePair> param = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url, "GET", param);

JSONObject songs= json.getJSONObject("songs");

如何将"songs" 转换为 JSONArray?

【问题讨论】:

    标签: java arrays json


    【解决方案1】:

    类似这样的:

    JSONObject songs= json.getJSONObject("songs");
    Iterator x = songs.keys();
    JSONArray jsonArray = new JSONArray();
    
    while (x.hasNext()){
        String key = (String) x.next();
        jsonArray.put(songs.get(key));
    }
    

    【讨论】:

      【解决方案2】:

      甚至更短并且带有 json 函数:

      JSONObject songsObject = json.getJSONObject("songs");
      JSONArray songsArray = songsObject.toJSONArray(songsObject.names());
      

      【讨论】:

        【解决方案3】:

        您的响应应该是这样的,才能被限定为 Json Array。

        {
          "songs":[
            {"2562862600": {"id":"2562862600", "pos":1}},  
            {"2562862620": {"id":"2562862620", "pos":1}},  
            {"2562862604": {"id":"2562862604", "pos":1}},  
            {"2573433638": {"id":"2573433638", "pos":1}}
          ]
        }
        

        您可以按如下方式解析您的响应

        String resp = ...//String output from your source
        JSONObject ob = new JSONObject(resp);  
        JSONArray arr = ob.getJSONArray("songs");
        
        for(int i=0; i<arr.length(); i++){   
          JSONObject o = arr.getJSONObject(i);  
          System.out.println(o);  
        }
        

        【讨论】:

          【解决方案4】:

          要反序列化响应需要使用HashMap:

          String resp = ...//String output from your source
          
          Gson gson = new GsonBuilder().create();
          gson.fromJson(resp,TheResponse.class);
          
          class TheResponse{
           HashMap<String,Song> songs;
          }
          
          class Song{
            String id;
            String pos;
          }
          

          【讨论】:

            【解决方案5】:
            JSONObject songs= json.getJSONObject("songs");
            

            使用 JSONArray 进行直接转换

            JSONArray array = (JSONArray)songs.get("songs");
            

            【讨论】:

              猜你喜欢
              • 2011-11-03
              • 2016-02-09
              • 2018-01-07
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多