以 JSON 格式获取 POST 结果

我正在使用 POST 发送数据。我用 JSON 得到了答案。如果我使用纯文本而不是 JSON,它可以工作,但它不适用于 JSON。


我在应用程序中没有收到任何错误屏幕


if (status) = true -> 注册 OK


进口:


import android.content.Intent;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;


import com.android.volley.AuthFailureError;

import com.android.volley.Request;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.StringRequest;

import com.android.volley.toolbox.Volley;


import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;


import java.util.HashMap;

import java.util.Map;


import javax.xml.transform.Result;

JSON:


[{"status":true,"result":"registerSuccessful","message":"Register succeeded"}]

爪哇代码:


private void registernewuser() {

        StringRequest request = new StringRequest(Request.Method.POST, registerUrl, new Response.Listener<String>() {

            @Override

            public void onResponse(String response) {


                try {


                    JSONObject jsonResponse = new JSONObject(response);

                    String RegisterResultString = jsonResponse.getString("status");


                    if (RegisterResultString.equals("true")) {

                        Toast.makeText(getApplicationContext(), "Successfully Registered User", Toast.LENGTH_LONG).show();

                        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);

                        startActivity(intent);

                    } else {

                        Toast.makeText(getApplicationContext(), "Sorry, Error Registering New User", Toast.LENGTH_LONG).show();

                    }


                } catch (JSONException e) {

                    e.printStackTrace();

                }

            }

        }, new Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError error) {


            }

        }) 


我在构建应用程序时没有遇到问题。但我找不到我的错。


慕盖茨4494581
浏览 202回答 3
3回答

眼眸繁星

您的JSON代码是JSONArray用单个JSONObject方括号的感觉。因此,只需设置jsonResponseas 的类型JSONArray并JSONObject使用该JSONArray.getJSONObject(0)方法获取 a 。JSONArray jsonResponse = new JSONArray(response);String registerResultString = jsonResponse.getJSONObject(0).getString("status");

呼如林

您需要将标头添加到您的请求中以指示 JSON 用法:request.addHeader("content-type",&nbsp;"application/json");否则它会将其解释为纯文本。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java