在Android中解析JSON数据时出错

I am developing a test Android application that must display some data from a MySQL db. Here are my logs:

enter image description here

Here the class JSONParser.java

package com.example.portal; 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;


public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "
");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;


    }

}

Here is the class I use to display the selected data:

package com.example.portal;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.portal.JSONParser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LogIn extends Activity{

    // Progress Dialog
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();

    EditText user;
    EditText pasword;

    // url to create new product
    private static String url_create_product = 

    "http://10.0.2.2/android_connect/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";






    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

         user=(EditText)findViewById(R.id.username);
         pasword=(EditText)findViewById(R.id.pasword);
         Button login= (Button) findViewById(R.id.loginbutton);

    /**
     * Handling all button click events
     * */

    // Listening to News Feed button click
    login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // Launching News Feed Screen
            //Intent i = new Intent(getApplicationContext(),MainMenu.class);
            //startActivity(i);
            new CreateNewProduct().execute();
        }
    });



    }



    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LogIn.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = user.getText().toString();
            String price = pasword.getText().toString();
            String description = user.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("description", description));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), 

        MainMenu.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {

                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }


    }

}

Here the PHP file:

    <?php

    /*
     * Following code will create a new product row
     * All product details are read from HTTP Post Request
    */

    // array for JSON response
    $response = array();
    $response["success"] = 0;
    $response["message"] = "No products found";

    // check for required fields
    if (isset($_POST['name']) && isset($_POST['price']) ) {

        $name = $_POST['name'];
        $price = $_POST['price'];


        // include db connect class
        require_once __DIR__ . '/db_connect.php';

        // connecting to db
        $db = new DB_CONNECT();

        // mysql inserting a new row
        $result = mysql_query("INSERT INTO products(name, price) VALUES('$name', '$price')");

        // check if row inserted or not
        if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
            echo json_encode($response);
        } else {
            // failed to insert row
            $response["success"] = 0;
            $response["message"] = "Oops! An error occurred.";

            // echoing JSON response
            echo json_encode($response);
            die();
        }
    } else {
        // required field is missing
        $response["success"] = 0;
        $response["message"] = "Required field(s) is missing";

        // echoing JSON response
        echo json_encode($response);
        die();
    }
    ?>

thanks

drus39136
drus39136 {“success”:0,“message”:“缺少必填字段”}此处没有参数发送
大约 5 年之前 回复
duanbai1027
duanbai1027 你可以在浏览器中调用url并在此处发布结果。
大约 5 年之前 回复
dongxin5054
dongxin5054 怎么样?我可以展示它
大约 5 年之前 回复
douzhui1972
douzhui1972 请显示你得到的json。
大约 5 年之前 回复

1个回答



您将获得异常</ p>

输入结束时的字符0 </ strong > </ p>

这意味着您的回复不是JSON,而是null。</ p>


原因可能是您的网址不支持POST请求和 您发送的帖子请求结果为空。</ p>

您的Url donot支持获取请求,并且您发送的Get请求结果为空。</ p>
</ blockquote>

查看以下链接,这些链接可能对您有所帮助</ p>

获取JSONException:输入结束于字符0 </ p>

org.json.JSON异常:字符0处的输入结束 </ p >
</ div>

展开原文

原文

You are getting exception

end of input at character 0 of

And that means your response in not JSON but null.

Reason can be that your url donot support POST Request and you are sending post request in result you are getting null.

Your Url donot support Get Request and You are sending Get Request in result you are getting null.

have a look at below link these links might help you

Getting a JSONException: end of input at character 0

org.json.JSON Exception : End of input at character 0

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐