您好我正在研究动态Android应用程序,我有以下json。阅读每一行很好我已经弄清楚如何在java中做到这一点(请记住我刚开始使用json昨天)如何在java中读取说明item2的内部数组到一个ArrayList我需要某种循环添加到字符串数组的屏幕截图链接。感谢您对我的问题的任何帮助。
"Manager":
[
{
"name" : "Sample item",
"icon" : "http://www.test.com/icon.png",
"link" : "http://www.test.com/sample.zip",
"summary" : "sample summary here",
"screenshots": [
"http://test.com/link2screenshot1.png",
"http://test.com/link2screenshot2.png"
]
},
{
"name" : "Sample item2",
"icon" : "http://www.test.com/icon2.png",
"link" : "http://www.test.com/sample2.zip",
"summary" : "sample summary here2",
"screenshots": [
"http://test.com/2/link2screenshot1.png",
"http://test.com/2/link2screenshot2.png"
]
}
]
=== EDIT ===
好的,这是最终解决方案,以下方法将从网址读取json并拉出我想要的感谢ninetwozero
public ArrayList<String> JSONInner(int count, String url, String outer, String inner){
ArrayList<String> linkArrayList = new ArrayList<String>();
URL u = null;
StringBuilder FileData = null;
try {
u = new URL(url);
String InputData = null;
InputStream is = null;
DataInputStream dis = null;
FileData = new StringBuilder();
is = u.openStream();
dis = new DataInputStream(new BufferedInputStream(is));
while ((InputData = dis.readLine()) != null) {
FileData.append(InputData);
}
is.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject json = null;
try {
json = new JSONObject(FileData.toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
if(FileData.toString() != null) {
try {
JSONArray managerArray = json.getJSONArray(outer);
JSONObject managerObject = managerArray.optJSONObject(count);
JSONArray linkArray = managerObject.getJSONArray(inner);
for(int subCount = 0, maxSubCount = linkArray.length(); subCount < maxSubCount; subCount++){
linkArrayList.add( linkArray.getString( subCount ));
}
}catch (JSONException e){
e.printStackTrace();
}
}
return linkArrayList;
}
答案 0 :(得分:1)
我会按照以下方式进行:
//Init
ArrayList<String> linkArrayList = new ArrayList<String>();
JSONArray managerArray = new JSONArray(yourString);
//Iterate over the top-level array
for( int count = 0, max = managerArray.length(); count < max; count++ ) {
//Get the current JSONObject & the link array
JSONObject managerObject = managerArray.optJSONObject(count);
JSONArray linkArray = managerObject.getJSONArray("screenshots");
//Iterate over the screenshots
for(
int subCount = 0, maxSubCount = linkArray.length();
subcount < maxSubCount;
subCount++
) {
//Let's store the String
linkArrayList.add( linkArray.getString( subCount );
}
}
如果您正在寻找,请告诉我。 : - )
编辑:但是,这将为您提供所有链接 - 如果您只想要数组项目#2,那么您可以删除外部循环并声明以下内容:
int count = 0; //The 0 should be the index of your item