Parsing JSON Array within JSON Object

后端 未结 5 1622
梦毁少年i
梦毁少年i 2020-11-27 14:45

I have some JSON with the following structure:

{\"source\":[
           {\"name\":\"john\",\"age\":20},
           {\"name\":\"michael\",\"age\":25},
                


        
相关标签:
5条回答
  • 2020-11-27 15:02

    line 2 should be

    for (int i = 0; i < jsonMainArr.size(); i++) {  // **line 2**
    

    For line 3, I'm having to do

        JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());
    
    0 讨论(0)
  • 2020-11-27 15:11

    Your code is fine, just replace the following line:

    JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
    

    with this line:

    JSONArray jsonMainArr = mainJSON.getJSONArray("source");
    
    0 讨论(0)
  • 2020-11-27 15:16

    This could be an answer to your question:

    JSONArray msg1 = (JSONArray) json.get("source");
    for(int i = 0; i < msg1.length(); i++){
      String name = msg1.getString("name");
      int age     = msg1.getInt("age");
    }
    
    0 讨论(0)
  • 2020-11-27 15:21

    mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.

    The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)

    Try this:

    JSONArray jsonMainArr = mainJSON.getJSONArray("source"); 
    
    0 讨论(0)
  • 2020-11-27 15:23
    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
          sb.append((char) cp);
        }
        return sb.toString();
      }
    
     String jsonText = readAll(inputofyourjsonstream);
     JSONObject json = new JSONObject(jsonText);
     JSONArray arr = json.getJSONArray("sources");
    

    Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:

    arr.getJSONObject(index)
    

    to get the objects inside of the array.

    0 讨论(0)
提交回复
热议问题