简体   繁体   English

JSON Android错误解析数据

[英]JSON Android Error parsing data

please I have problem with my JSON webservice. 请我的JSON Web服务有问题。 When I call function , I am getting this exception: 当我调用function时,我得到了这个异常:

03-19 15:14:10.013: E/JSON Parser(12011): Error parsing data org.json.JSONException: End of input at character 0 of 
03-19 15:14:10.013: W/System.err(12011): java.util.concurrent.ExecutionException: java.lang.NullPointerException
03-19 15:14:10.013: W/System.err(12011):    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:223)
03-19 15:14:10.013: W/System.err(12011):    at java.util.concurrent.FutureTask.get(FutureTask.java:82)
03-19 15:14:10.013: W/System.err(12011):    at android.os.AsyncTask.get(AsyncTask.java:482)
03-19 15:14:10.013: W/System.err(12011):    at dp.zajac.facerecognizer3.FromCameraMainSceneFragment.uploadFaceToServer(FromCameraMainSceneFragment.java:657)
03-19 15:14:10.013: W/System.err(12011):    at dp.zajac.facerecognizer3.FromCameraMainSceneFragment.onSingleFaceDialogPositiveClickWithDatabases(FromCameraMainSceneFragment.java:635)
03-19 15:14:10.013: W/System.err(12011):    at dp.zajac.savefacesdialogs.FaceToSaveDialog$3.onClick(FaceToSaveDialog.java:162)
03-19 15:14:10.013: W/System.err(12011):    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
03-19 15:14:10.013: W/System.err(12011):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 15:14:10.013: W/System.err(12011):    at android.os.Looper.loop(Looper.java:137)
03-19 15:14:10.013: W/System.err(12011):    at android.app.ActivityThread.main(ActivityThread.java:4830)
03-19 15:14:10.013: W/dalvikvm(12011): threadid=13: thread exiting with uncaught exception (group=0x416742a0)
03-19 15:14:10.023: W/System.err(12011):    at java.lang.reflect.Method.invokeNative(Native Method)
03-19 15:14:10.023: W/System.err(12011):    at java.lang.reflect.Method.invoke(Method.java:511)
03-19 15:14:10.023: W/System.err(12011):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
03-19 15:14:10.023: W/System.err(12011):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
03-19 15:14:10.023: W/System.err(12011):    at dalvik.system.NativeStart.main(Native Method)
03-19 15:14:10.033: W/System.err(12011): Caused by: java.lang.NullPointerException
03-19 15:14:10.033: W/System.err(12011):    at dp.fedorko.client.jsonClient.doInBackground(jsonClient.java:58)
03-19 15:14:10.033: W/System.err(12011):    at dp.fedorko.client.jsonClient.doInBackground(jsonClient.java:1)
03-19 15:14:10.043: W/System.err(12011):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-19 15:14:10.043: W/System.err(12011):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-19 15:14:10.043: W/System.err(12011):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-19 15:14:10.043: W/System.err(12011):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-19 15:14:10.043: W/System.err(12011):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-19 15:14:10.043: W/System.err(12011):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-19 15:14:10.043: W/System.err(12011):    at java.lang.Thread.run(Thread.java:856)

I use this code for calling JSON web service : 我使用以下代码来调用JSON Web服务

 protected String doInBackground(Object... params) {
        if((Integer)params[0]==0)
            return null;
        if((Integer)params[0]==1){
            // Building Parameters
            List<NameValuePair> params1 = new ArrayList<NameValuePair>();
            params1.add(new BasicNameValuePair("name", "mobilefirst"));
            //params1.add(new BasicNameValuePair("vector", "0 1 2 1 0"));
            //params1.add(new BasicNameValuePair("personid", "1"));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params1);
            Log.d("Create Response", json.toString());
            return json.toString();
        }
        return null;
    }

And this is jsonParser code: 这是jsonParser代码:

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 + "\n");
            }
            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 my web service code : 这是我的网络服务代码

<?php
 //require_once __DIR__ . '/php_connect.php';
/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

// array for JSON response
$response = array();

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

    $name = $_POST['name'];
    //$vector = $_POST['vector'];
    //$personid = $_POST['personid'];

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

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

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

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "User 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);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

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

Please where can be problem? 请哪里有问题? I am stuck on this. 我一直坚持下去。 I do not see where is the problem. 我看不出问题出在哪里。

Thank you for every answer. 谢谢你的回答。

Martin 马丁

Your JSON data in not complete or not properly formatted. 您的JSON数据不完整或格式不正确。 Validate first before you construct. 在构造之前先进行验证。 Don't trust the source. 不要相信来源。

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

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