2017-04-05 154 views
0

我有一个小的功能,使一个JSON API请求,并返回一个字符串Postexecute:JSON有多个同名的对象

public class fetch extends AsyncTask<URL, Void, String> { 
    @Override 
    protected String doInBackground(URL... urls) { 
     URL search = urls[0]; 
     String results = null; 
     try { 
      results = getResponse(search); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return results; 
    } 

现在我希望得到一些具体的JSON对象,但我有多个同一物品:

[ 
    { 
     "A1": { 
      "about": { 
       "IDs": [19] 
      }, , 
      "value": 1 
     }, 
     "A2": { 
      "about": { 
       "IDs": [19] 
      }, 
      "value": 2 
     } 
    }, 
    { 
     "A1": { 
      "about": { 
       "IDs": [20] 
      }, , 
      "value": 3 
     }, 
     "A2": { 
      "about": { 
       "IDs": [20] 
      }, 
      "value": 4 
     } 
    } 
] 

我该怎么做?

+1

'[...]'代表阵列。如果您知道数组中的哪个项目,那么只需使用该项目的索引,可能通过像'yourJsonArray.get(index)'这样的东西。 – Pshemo

回答

2

你在那里有一组地图对象。

看看它在这个美丽的JSON编辑:http://jsoneditoronline.org/?id=78f6765cb52e5403d01a8feead392611

你会首先访问数组元素0或1,然后访问地图对象。

secondObject = myjsonarray.getJsonObject(1) 
a2 = secondObject.getJsonObject("A2") 
thisisfour = a2.getInt("value") 

或者全部串在一起:

thisisfour = myjsonarray.getJsonObject(1).getJsonObject("A2").getInt("value") 

相关Javadoc参考:

http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html http://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html

+0

有引用链接总是有帮助的'AsyncTask'建议Android不是JavaEE。无论如何+1一般的解决方案应该在大多数环境中相似。 – Pshemo