实际上 return 来自 class 的 JSONObject 被使用

Effectively return a JSONObject from a class to be used

我很难在另一个 class 中使用 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 执行 class(基本我知道),

我正在尝试在我的主 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 块:

 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");

在我的 JSON 中查询 class returns 预期结果(分配给文本字段时)

你只需要try & catch这行代码

url.setText(Obj.getString("url"));

因为如果 "url" 键没有映射字符串,org.json.JSONObject#getString 将抛出 JSONException

或者,您可以使用 org.json.JSONObject#optString(java.lang.String)。如果不存在这样的映射,它不会抛出 JSONException 和 returns 空字符串。