为什么我不能在JSONObject上使用if或switch语句?

3

我只是有一个AsyncTask,使用监听器与主活动进行通信。当响应到达时,第一个Toast将以正确的值显示。问题在于,在try catch中,我无法恢复这些值。因此,if或switch不再起作用。

@Override
public void OnAsyncTaskComplete(String response) {

    Toast.makeText(getContext(),((ActivityLogin) getActivity()).choiceButton+" result: "+response, Toast.LENGTH_LONG).show();

    try {

        JSONObject obj = new JSONObject(response);

        String objservice = obj.getString("service");
        String objstatuCode = obj.getString("status-code");
        String objdescription = obj.getString("status-description");

        JSONObject result = obj.getJSONObject("result");

        if(!objstatuCode.equals("200") || objstatuCode.equals(null)){
            Toast.makeText(getContext(), objstatuCode+"", Toast.LENGTH_SHORT).show();
            return;
        } else {
            Toast.makeText(getContext(), objstatuCode+"", Toast.LENGTH_SHORT).show();
            return;
        }

    } catch (JSONException e){
        e.printStackTrace();
    }
}

enter image description here


1
分享您的JSON响应与问题。 - AskNilesh
分享回应在这里。 - Sandeep Sankla
首先,将您的条件交换为 if(objstatuCode.equals(null) || !objstatuCode.equals("200") ){}。如果您的状态代码是整数,请使用 getInt。 - Sreedhu Madhu
不起作用,它还是一样的。 - Giorgio Cafiso
1个回答

1
我假设你遇到了 JSONException为什么会出现这种情况呢?
Thrown to indicate a problem with the JSON API

来自问题

 String objstatuCode = obj.getString("status-code");
 JSONObject result = obj.getJSONObject("result");

你的 JSON VALUE (KEY=status-code)int。你需要纠正它。
它必须是:
int objstatuCode = obj.getInt("status-code");
String result    = obj.getString("result");

那么

if(objstatuCode!=200){
                Toast.makeText(getContext(), objstatuCode+"", Toast.LENGTH_SHORT).show();
                return;
            } else {
                Toast.makeText(getContext(), objstatuCode+"", Toast.LENGTH_SHORT).show();
                return;
            }

@GiorgioCafiso 清理并重新构建,让我通知您。 - IntelliJ Amiya
2
问题解决了,谢谢。错误在于我在同一个活动中有其他调用,其中结果是一个数组。 - Giorgio Cafiso
@GiorgioCafiso 前进! - IntelliJ Amiya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接