简体   繁体   English

如何解析来自服务器的 JSON 响应并进行比较

[英]how to parse JSON response from server and use it in comparison

I want to parse JSON response from server but I m unable to do it.我想解析来自服务器的 JSON 响应,但我无法做到。 please help me请帮我

server response for connection success is连接成功的服务器响应是

Database connection success....{"server_response":[{"code":"reg_true","0":"message=>Registration Success...Thank you....."}]}

I want to parse it and use server_response and code values in comparing so I can execute IF statement When I debug my code.我想解析它并在比较中使用 server_response 和代码值,这样我就可以在调试代码时执行 IF 语句。 It shows that json = Database connection success....{"server_response":[{"code":"reg_true","0":"message=>Registration Success...Thank you....."}]}显示json = 数据库连接成功....{"server_response":[{"code":"reg_true","0":"message=>Registration Success...Thank you....."}] }

but then it jump to catch (JSONException e) please help this is my code但是然后它跳转到捕获(JSONException e)请帮助这是我的代码

        JSONObject jsonObject = new JSONObject(json);
        JSONArray jsonarry= jsonObject.getJSONArray("server_response");
        JSONObject JO = jsonarry.getJSONObject(0);
        String code = JO.getString("code");
        String message = JO.getString("message");

        if (code.equals("reg_true")) {

            showDialog("Registration Success",code,message);

        } else if (code.equals("reg_false")) {


            showDialog("Registration Failed",code, message);

        } else if (code.equals("login_true")) {
            Intent intent = new Intent(activity, HomeActivity.class);
            intent.putExtra("message", message);
            activity.startActivity(intent);
        } else if (code.equals("login_false")) {
            showDialog("Login Error...",code,message);
        }


    } catch (JSONException e) {
        e.printStackTrace();
    }
}
   public void showDialog(String title, String code, String message)
   {

      builder.setTitle(title);
       if(code.equals("reg_true")||code.equals("reg_false"))
       {

           builder.setMessage(message);
           builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   dialog.dismiss();
                   activity.finish();
               }

           });

The exception is because of the special symbol => inside your json response.例外是因为 json 响应中的特殊符号 => 。 Send a valid json string in valid format as:以有效格式发送有效的 json 字符串,如下所示:

Database connection success....{"server_response":[{"code":"reg_true","0":"message Registration Success...Thank you....."}]}

You can try it.你可以试试看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM