我正在努力在另一个类中使用一个类中的 JSON 对象..我目前有:
public String URL;
public JSONObject ResultArray;
public StackTraceElement[] Error;
public void ExecJSONRequest(){
JSONObject json = null;
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(this.URL);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
// Look for Errors
} catch (ClientProtocolException e) {
this.Error = e.getStackTrace();
} catch (IOException e) {
this.Error = e.getStackTrace();
}
try {
// Get Results from URL & Populate for return
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0);
this.ResultArray = json;
// Look for Errors
} catch (JSONException e) {
this.Error = e.getStackTrace();
}
}
这是我的 JSON 执行类(我知道的基本),
我尝试在我的主要 Activity 中使用 ResultArray
:
TextView url = (TextView) findViewById(R.id.url);
JSONQuery JSONQ = new JSONQuery();
JSONQ.URL = "192.168.0.12/Testing/index.php";
JSONQ.ExecJSONRequest();
JSONObject Obj = JSONQ.ResultArray;
url.setText(Obj.getString("url"));
Android studio 报告未处理的 JSON 异常。
使用 try/catch block :
try {
JSONQuery JSONQ = new JSONQuery();
JSONQ.URL = "192.168.0.12/Testing/index.php";
JSONQ.ExecJSONRequest();
JSONObject Obj = JSONQ.ResultArray;
url.setText(Obj.getString("url"));
}catch(Exception E){
E.printStackTrace();
}
尽管我的字段未填充,但是否消除了此错误?
<小时/>更新。使用:
// Get Results from URL & Populate for return
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0);
//this.ResultArray = json;
json.getString("url");
在我的 JSONQuery 类中返回预期结果(分配给文本字段时)
最佳答案
你只需要 try catch 这行代码
url.setText(Obj.getString("url"));
因为如果“url”键没有映射字符串,org.json.JSONObject#getString
将抛出 JSONException
。
或者,您可以使用 org.json.JSONObject#optString(java.lang.String)
代替。它不会抛出 JSONException
并在不存在此类映射的情况下返回空字符串。
关于java - 有效地从要使用的类返回 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27832169/