解析数据时出错org.json.JSONException类型为java.lang.String的值

时间:2016-04-12 05:19:45

标签: java android json

private EditText name,email,password,phone;
    private Button reg_btn;
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL = "http://vichomes.softcorp.ca/android/register/";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

我的signup.java课程。我向服务员发送用户证书

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sign_up);


        name=(EditText)findViewById(R.id.name);
        email=(EditText)findViewById(R.id.email1);
        password=(EditText)findViewById(R.id.password1);
        phone=(EditText)findViewById(R.id.phone);
        reg_btn=(Button)findViewById(R.id.button3);

        reg_btn.setOnClickListener(this);


    }


    public void onClick(View v) {
        // TODO Auto-generated method stub

        new CreateUser().execute();

        }

    class CreateUser extends AsyncTask<String, String, String> {

        boolean failure = false;
        String namestr = name.getText().toString();
        String emailstr = email.getText().toString();
        String passwordstr = password.getText().toString();
        String phonestr= phone.getText().toString();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(sign_up.this);
            pDialog.setMessage("Successfull");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
  

此处转换为JSON

      @Override
        protected String doInBackground(String... args){

            // TODO Auto-generated method stub
            // Check for success tag
            int success;


            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("name", namestr));
                params.add(new BasicNameValuePair("email", emailstr));
                params.add(new BasicNameValuePair("password",passwordstr));
                params.add(new BasicNameValuePair("phone", phonestr));

                Log.d("request!", "starting");

                //Posting user data to script
                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
  

打印完整的json响应

                Log.d("sign up attempt", json.toString()
  

json成功元素

                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User Created!", json.toString());
                    Intent i= new Intent(sign_up.this,donation.class);
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                }
else{
                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);

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

            return null;


        }

        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(sign_up.this, file_url, Toast.LENGTH_LONG).show();
            }

        }
    }




  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if(id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
  

XML CODE OF SIGN UP画面。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1F874E"
    android:orientation="vertical">

<TextView
    android:layout_width="221dp"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Sign Up"
    android:id="@+id/textView2"
    android:textColor="#FFFFFF"
    android:textStyle="bold"
    android:textSize="40px"
    android:layout_marginLeft="20dp"
    android:layout_marginTop="10dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Name"
    android:id="@+id/textView3"
    android:layout_marginTop="20dp"
    android:layout_marginLeft="20dp"
    android:textSize="20dp"
    android:textStyle="bold"/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/name"
    android:layout_gravity="center_horizontal" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Email"
    android:id="@+id/textView4"
    android:layout_marginTop="20dp"
    android:layout_marginLeft="20dp"
    android:textSize="20dp"
    android:textStyle="bold"/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textEmailAddress"
    android:ems="10"
    android:id="@+id/email1"
    android:layout_gravity="center_horizontal" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Password"
    android:id="@+id/password5"
    android:layout_marginTop="20dp"
    android:layout_marginLeft="20dp"
    android:textSize="20dp"
    android:textStyle="bold"/>

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:ems="10"
    android:id="@+id/password1" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Confirm Password"
        android:id="@+id/textView"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:textSize="20dp"
        android:textStyle="bold"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/password2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone"
        android:id="@+id/textView16"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:textSize="20dp"
        android:textStyle="bold"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:ems="10"
        android:id="@+id/phone" />

    <Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Submit"
    android:id="@+id/button3"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="40dp"
    android:layout_marginLeft="0dp"
    android:textSize="20dp"
    android:textStyle="bold"
        android:onClick="Submit"/>

</LinearLayout>
  

例外记录

 Error parsing data org.json.JSONException: Value <html> of type java.lang.String cannot be converted to JSONObject
    04-12 10:00:08.302 6397-6478/com.virasatsolutions.www.donapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
                                                                                   Process: com.virasatsolutions.www.donapp, PID: 6397
                                                                                   java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                                       at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                                                       at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                                       at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                                       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                                       at java.lang.Thread.run(Thread.java:818)
                                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
                                                                                       at com.virasatsolutions.www.donapp.sign_up$CreateUser.doInBackground(sign_up.java:169)
                                                                                       at com.virasatsolutions.www.donapp.sign_up$CreateUser.doInBackground(sign_up.java:129)
                                                                                       at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                                                                                       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                                                                                       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                                                                                       at java.lang.Thread.run(Thread.java:818) 
    04-12 10:00:08.437 6397-6422/com.virasatsolutions.www.donapp W/EGL_emulation: eglSurfaceAttrib not implemented
    04-12 10:00:08.438 6397-6422/com.virasatsolutions.www.donapp W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xac43fe00, error=EGL_SUCCESS
    04-12 10:00:08.530 6397-6422/com.virasatsolutions.www.donapp E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae6f5af0
    04-12 10:00:08.542 6397-6422/com.virasatsolutions.www.donapp E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae6f5460
    04-12 10:00:08.783 6397-6397/com.virasatsolutions.www.donapp E/WindowManager: android.view.WindowLeaked: Activity com.virasatsolutions.www.donapp.sign_up has leaked window com.android.internal.policy.PhoneWindow$DecorView{954561b V.E...... R......D 0,0-1026,348} that was originally added here
                                                                                      at android.view.ViewRootImpl.<init>(ViewRootImpl.java:368)
                                                                                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
                                                                                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                                                                                      at android.app.Dialog.show(Dialog.java:319)
                                                                                      at com.virasatsolutions.www.donapp.sign_up$CreateUser.onPreExecute(sign_up.java:144)
                                                                                      at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
                                                                                      at android.os.AsyncTask.execute(AsyncTask.java:551)
                                                                                      at com.virasatsolutions.www.donapp.sign_up.onClick(sign_up.java:125)
                                                                                      at android.view.View.performClick(View.java:5198)
                                                                                      at android.view.View$PerformClick.run(View.java:21147)
                                                                                      at android.os.Handler.handleCallback(Handler.java:739)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 个答案:

答案 0 :(得分:1)

  

你有错误..

   Value <html> of type java.lang.String cannot be converted to JSONObject

您的api服务似乎没有得到很好的响应。实际上api存在一些问题。

如果任何REst-api返回一些html标记值,则表示由于某些exception mismmatch而导致service中出现input一些String

我无法告诉你确切的原因,但还有其他几个原因。

我认为您应该对从api网址收到的String urlResponse = "{}" // suppose this variable holds the response from the URL. //then put a check to this variable such that if(urlResponse.startsWith("{") ){ //in this block you may parse your response from String to JSONObject. JSONObject v_obj = (JSONObject) new parser().parse(urlResponse); }else if(urlResponse.startsWith("[")){ //in this block you may parse your response from String to JSONArray. JSONArray v_obj = (JSONArray) new parser().parse(urlResponse); }else{ //write if you don't receive correct response. } 变量添加一项检查。

urlResponse.startsWith("{")
  

注意: - 如果true返回JSONObject,那么它就是urlResponse.startsWith("[")类型。如果true返回JSONArray,则其中包含class CustomButton: UIButton { override func intrinsicContentSize() -> CGSize { return titleLabel?.intrinsicContentSize() ?? super.intrinsicContentSize() } }

谢谢..

答案 1 :(得分:0)

API中的问题是它返回HTML内容。

要测试它并找出问题,请使用Postman或任何其他Restful客户端发送请求并获取响应。