首页 > 解决方案 > 为什么我无法转换我的服务器响应并出现错误?

问题描述

我从网络服务器接收一些数据。它只有两个部分,名称和 ID。不知道为什么它不工作尝试使用 jsonarray 和 json 对象,但都没有工作。我收到了响应,但无法将其转换为我可以在程序的其他部分使用响应的数据设置。不知道我做错了什么。

我的回复代码:

try {
        Data User = new Data();
        JSONObject UserName= new JSONObject();
        JSONObject user = (UserName.getJSONObject(res));
        User.setUserID(user.getInt("UserID"));
        User.setUserName(user.getString("UserName"));
    } catch (JSONException e) {
        e.printStackTrace();
    }



}


    //  System.out.println(getResponse);



@Override
protected String doInBackground(Void... v) {
    HashMap<String, String> params = new HashMap<>();
    params.put(Config.KEY_UserEmail, UserEMail);
    params.put(Config.KEY_Userloggedstatus, Loggedstatus);
    RequestHandler rh = new RequestHandler();
    String res = rh.sendPostRequest(Config.URL_ADDACCOUNTLOGIN, params);
    Log.d(TAG, "doInBackground: "+ params);
    Log.d(TAG, "doInBackground: SENDED!");
    Log.d(TAG, "doInBackground: "+ res);
    return res;

}

那是我的服务器响应:

doInBackground: {"UserName":"Felix","UserID":6}

这就是错误:

 org.json.JSONException: Value {"UserName":"Felix","UserID":6} of type org.json.JSONObject cannot be converted to JSONArray

上次也是:

 org.json.JSONException: No value for Result

我应该如何更改我的代码以正确接收它并可以使用响应?

标签: androidjson

解决方案


试试这个。为我工作。

try {
        String res = "{\"UserName\":\"Felix\",\"UserID\":6}";
        Data User = new Data();
        org.json.JSONObject user = new JSONObject(res);
        User.setUserID(user.getInt("UserID"));
        User.setUserName(user.getString("UserName"));
        System.out.println(User.getUserID());
        System.out.println(User.getUserName());
    } catch (JSONException e) {
        e.printStackTrace();
    }

推荐阅读