Java 使用 getJSONObject(int)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23703431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use getJSONObject(int)
提问by AquaMorph
I'm trying to parse some JSON. Here is the code. frc-manual.usfirst.org/a/GetAllItems/ManualID=3I have been trying for several hours to get it work but every example I have seen online uses getJSONObject(int) but I can only use getJSONObject(String). This is making impossible. Am I overlooking something?
我正在尝试解析一些 JSON。这是代码。frc-manual.usfirst.org/a/GetAllItems/ManualID=3我已经尝试了几个小时来让它工作,但我在网上看到的每个例子都使用 getJSONObject(int) 但我只能使用 getJSONObject(String)。这是不可能的。我是否忽略了什么?
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.annotation.SuppressLint;
public class JSON {
private String html = "html";
private String version = "version";
private String pageString = null;
private String urlString = "http://frc-manual.usfirst.org/a/GetAllItems/ManualID=3";
public volatile boolean parsingComplete = true;
public JSON(String page){
this.pageString = page;
}
public String getHTML(){
return html;
}
public String getVersion(){
return version;
}
@SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
JSONObject head = reader.getJSONObject("data").getJSONObject("SubChapter").getJSONObject("3").getJSONObject("children").getJSONObject(pageString);
if(head != null){
html = head.getString("item_content_text");
html = html + head.length();
for(int i = 0; i < head.length();i++){
JSONObject children = head.getJSONObject(i);
if(children != null){
html = html + children.getString("item_content_text");
}
}
}
//html = html + listFromJsonSorted(head.getJSONObject("children"));
JSONObject main = reader.getJSONObject("data");
version = main.getString("LatestManualUpdate");
parsingComplete = false;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fetchJSON(){
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
String data = convertStreamToString(stream);
readAndParseJSON(data);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
return s.hasNext() ? s.next() : "";
}
}
回答by Rajat Singhal
You are only able to use getJSONObject(String)not getJSONObject(int)because the method only takes String.. Check documentation here..
您只能使用getJSONObject(String)notgetJSONObject(int)因为该方法仅采用 String ..在此处查看文档..
The reason that is the because the keys in json are always strings only.. read here
原因是因为 json 中的键始终只是字符串..在这里阅读
I think you are looking to retrieve an int value from the json but you got confused.. The way to do that would be getInt("key_name")if the json indeed has a key with int value..
我认为您正在寻找从 json 中检索 int 值,但您感到困惑.. 这样做的方法是getInt("key_name")如果 json 确实有一个带有 int 值的键..
回答by Tiago Henrique Engel
Probably what you are seeing in this example is a JSONArray.
您在本示例中看到的可能是 JSONArray。
JSONArray arr = json.getJSONArray("array");
JSONObject obj = arr.getJSONObject(0);
In your case, i don't see any array in this JSON, headin your code is a JSONObject. To get the item_content_text you just need head.getString("item_content_text");
在你的情况下,我在这个 JSON 中没有看到任何数组,你的代码中的头部是一个 JSONObject。要获得您只需要的 item_content_texthead.getString("item_content_text");
You can do this to get all childrens in your JSON:
您可以这样做以获取 JSON 中的所有子项:
html = head.getString("item_content_text");
JSONObject children = head;
while (children.containsKey("children")) {
children = children.getJSONObject("children");
html += children.getString("item_content_text");
}
回答by ND27
Sure you can, just that I think your "head" variable should have a return type of JSONArray instead of JSONObject.
当然可以,只是我认为你的“头”变量应该有一个 JSONArray 而不是 JSONObject 的返回类型。
I have this code running in my program -
我在我的程序中运行了这段代码 -
//response = some http response
final JSONObject object = new JSONObject(response);
final JSONArray array = object.getJSONArray("repeatedStuff"); //$NON-NLS-1$
Assert.assertEquals(2, array.length());
for (int i = 0; i < array.length(); i++) {
final JSONObject element = array.getJSONObject(i);
//do something
}
Also you may refer this link to see what they are doing - android: The method getJSONObject(int) in the type JSONArray is not applicable for the arguments (String)
您也可以参考此链接以查看他们在做什么 - android:JSONArray 类型中的方法 getJSONObject(int) 不适用于参数 (String)
Let me know if that helped!
如果有帮助,请告诉我!

