How to convert JSONObjects to JSONArray?

后端 未结 4 1766
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 12:12

I have a response like this:

{
 \"songs\":{
          \"2562862600\":{\"id\":\"2562862600\"\"pos\":1},
          \"2562862620\":{\"id\":\"2562862620\"\"pos\"         


        
相关标签:
4条回答
  • 2020-11-28 12:35

    Even shorter and with json-functions:

    JSONObject songsObject = json.getJSONObject("songs");
    JSONArray songsArray = songsObject.toJSONArray(songsObject.names());
    
    0 讨论(0)
  • 2020-11-28 12:37

    Your response should be something like this to be qualified as Json Array.

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

    You can parse your response as follows

    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);  
    }
    
    0 讨论(0)
  • 2020-11-28 12:39

    To deserialize the response need to use 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;
    }
    
    0 讨论(0)
  • 2020-11-28 12:43

    Something like this:

    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));
    }
    
    0 讨论(0)
提交回复
热议问题