GVKun编程网logo

解析数据org.json.JSONException时出错:在字符0的输入结束(json字符串解析出错)

19

在本文中,我们将给您介绍关于解析数据org.json.JSONException时出错:在字符0的输入结束的详细内容,并且为您解答json字符串解析出错的相关问题,此外,我们还将为您提供关于ajax请

在本文中,我们将给您介绍关于解析数据org.json.JSONException时出错:在字符0的输入结束的详细内容,并且为您解答json字符串解析出错的相关问题,此外,我们还将为您提供关于ajax请求json格式的数据,在经过interceptor时出现JSONException、android – org.json.JSON异常:字符0的输入结束、android – 从url解析JSON,异常:解析数据时出错org.json.JSONException:字符115处的未终止数组、android – 解析数据时出错org.json.JSONException:值<?xml的java.lang.String类型无法转换为JSONArray的知识。

本文目录一览:

解析数据org.json.JSONException时出错:在字符0的输入结束(json字符串解析出错)

解析数据org.json.JSONException时出错:在字符0的输入结束(json字符串解析出错)

解析JSON时出现错误。解析数据org.json.JSONException时出错:输入的第0个字符。

错误日志:

04-19 20:51:00.635: E/ViewRootImpl(24857): sendUserActionEvent() mView == null04-19 20:51:00.635: E/ViewRootImpl(24857): sendUserActionEvent() mView == null04-19 20:51:03.320: E/ViewRootImpl(24857): sendUserActionEvent() mView == null04-19 20:51:10.215: E/JSON Parser(24857): Error parsing data org.json.JSONException: End of input at character 0 of 04-19 20:51:35.600: E/ViewRootImpl(24857): sendUserActionEvent() mView == null

这是在UserFunction类中调用函数的代码:

    pTotalPrice=new double[cartSize]; // store array of totalprice    /** To be sent to DB **/    sPID = new String[cartSize];    sProduct = new String[cartSize];    sQuantity = new String[cartSize];    sTotalPrice = new String[cartSize];    if(cartSize >0)    {        for(int i=0;i<cartSize;i++)        {               final int counter = i;            // Get probuct data from product data arraylist            String pID = aController.getProducts(i).getProductId();            sPID[i] = pID;            String pName = aController.getProducts(i).getProductName();            sProduct[i] = pName;            double pPrice   = aController.getProducts(i).getProductPrice();            int pQuantity   = aController.getProducts(i).getProductQuantity();            sQuantity[i] = Integer.toString(pQuantity);            pTotalPrice[i] = pPrice * pQuantity;            sTotalPrice[i] = Double.toString(pTotalPrice[i]);             }    pFinalPrice -= pTotalPrice[counter];sFinalPrice = Double.toString(pFinalPrice);    }          protected JSONObject doInBackground(String... args) {            UserFunctions userFunction = new UserFunctions();            JSONObject json = userFunction.orderDetails(username, sPID, sProduct, sQuantity, sTotalPrice, Double.toString(pFinalPrice));            Log.d("Button", "Order");            return json;        }

UserFunction类中的函数

/** * Function store order details **/public JSONObject orderDetails(String username, String[] pid, String[] products, String[] quantity, String[] totalprice, String finalprice) {    // Building Parameters    List params = new ArrayList();    params.add(new BasicNameValuePair("tag", order_tag));    params.add(new BasicNameValuePair("username", username));    params.add(new BasicNameValuePair("finalpice", finalprice));    for (int i = 0; i < pid.length; i++) {        params.add(new BasicNameValuePair("pid[i]", pid[i]));    }       for (int j = 0; j < products.length; j++) {        params.add(new BasicNameValuePair("products[j]", products[j]));    }    for (int k = 0; k < quantity.length; k++) {        params.add(new BasicNameValuePair("quantity[k]", quantity[k]));    }    for (int l = 0; l < totalprice.length; l++) {        params.add(new BasicNameValuePair("totalprice[l]", totalprice[l]));    }    JSONObject json = jsonParser.getJSONFromUrl(orderURL,params);    return json;}

Java解析器类:

public class JSONParser {static InputStream is = null;static JSONObject jObj = null;static String json = "";// constructorpublic JSONParser() {}public JSONObject getJSONFromUrl(String url, List params) {    // Making HTTP request    try {        // 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();    } 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();        Log.e("JSON", json);    } 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;}}

这是我的index.php API

else if ($tag == ''order'') {    $username = $_POST[''username''];    $finalprice = $_POST[''finalprice''];    $pid = $_POST[''pid''];    $quantity = $_POST[''quantity''];    $totalprice = $_POST[''totalprice''];            $response["successfullypost"] = 1;    $response["user"]["username"] = $username;    $response["user"]["finalprice"] = $finalprice;    $response["user"]["pid"] = $pid;    $response["user"]["quantity"] = $quantity;    $response["user"]["totalprice"] = $totalprice;    echo json_encode($response);    $uResult = mysql_query("SELECT * FROM users WHERE username = $username");    $uid = $uResult[''uid''];    $counter = sizeof($pid);    for ( $i=0; $i < $counter; $i++) {        $db-> orderdetails($uid, $pid[$i], $quantity[$i], $totalprice[$i], $finalprice);    }}else {    $response["error"] = 3;    $response["error_msg"] = "JSON ERROR";    echo json_encode($response);}

index.php调用此orderdetails函数

public function orderdetails ($uid, $pid, $quantity, $totalprice, $finalprice) {    $pResult = mysql_query("SELECT * FROM products WHERE pid = $pid");    $Product_ID = $pResult[''ProductID''];    $final = mysql_query("INSERT INTO vieworders (uid, ProductID, quantity, $totalprice, finalprice)         VALUES (''$uid'', ''$ProductID'', ''$quantity'', ''$totalprice'', ''$finalprice'')");}

新的JSON响应。尽管我必须要生产的产品不能显示阵列。为什么JSON标签显示“ i”而不是pid [i]?数量和总价相同

04-20 10:19:31.615: E/ViewRootImpl(20740): sendUserActionEvent() mView == null04-20 10:19:44.505: E/JSON(20740): {"tag":"order","success":0,"error":0,"successfullypost":1,"user":{"username":"zulanawi","finalprice":null,"pid":{"i":"0002"},"quantity":{"k":"3"},"totlaprice":{"l":"32.400000000000006"}}}{"success":0}

答案1

小编典典

完成!!!在将POST将String数组传递给PHP之后,我得到了答案。

/*** Function store order details**/public JSONObject orderDetails(String username, String[] pid, String[] products,    String[] quantity, String[] totalprice, String finalprice) {// Building ParametersList params = new ArrayList();params.add(new BasicNameValuePair("tag", order_tag));params.add(new BasicNameValuePair("username", username));params.add(new BasicNameValuePair("finalpice", finalprice));for (int i = 0; i < pid.length; i++) {    params.add(new BasicNameValuePair("pid[]", pid[i]));}   for (int j = 0; j < products.length; j++) {    params.add(new BasicNameValuePair("products[]", products[j]));}for (int k = 0; k < quantity.length; k++) {    params.add(new BasicNameValuePair("quantity[]", quantity[k]));}for (int l = 0; l < totalprice.length; l++) {    params.add(new BasicNameValuePair("totalprice[]", totalprice[l]));}JSONObject json = jsonParser.getJSONFromUrl(orderURL,params);return json;}

ajax请求json格式的数据,在经过interceptor时出现JSONException

ajax请求json格式的数据,在经过interceptor时出现JSONException

出现题目描述的问题的原因和对应的解决方法如下:

(1)json中有Date类型的数据,在进行json解析的时候出现改类型不能被正确解析。应该把属性的类定义为java.util.Date;

(2)Action中定义的方法不是要返回前台定义的属性,可是方法的名称是getXxx,jsonplugins把这个方法当作属性用反射的方式调用了,这样就会出行JSONexception。这种情况的解决方法有两种,一种是把方法名不要定义为getXxx,也可以再方法名前加@JSON(serialize=false)。

android – org.json.JSON异常:字符0的输入结束

android – org.json.JSON异常:字符0的输入结束

我正在尝试从android解析json,但我得到了这个奇怪的异常.我的json数据是

{“id”:”1″,”owner”:”1″,”name”:”gravitas”,”description”:”is a fest”,”start_time”:”0000-00-00 00:00:00″,”end_time”:”0000-00-00 00:00:00″,”venue”:”vellore”,”radius”:”10″,”lat”:”11″,”lng”:”11″,”type”:”type”,”ownername”:”dilip”,”noofpolls”:0,”noofquizes”:0,”peopleattending”:0,”result”:true}

在android我做

JSONObject j =new JSONObject(response);
Event pst = gson.fromJson(j.toString(),  Event.class);

我明白了:

org.json.JSONException: end of input at character 0 of

它出什么问题了?这是代码……

RestClient client = new RestClient("http://192.168.1.3/services/events/"+eve.getName());         
        try {
             Log.i("MY INFO", "calling boston");
            client.Execute(RequestMethod.POST);
        } catch (Exception e) {
            e.printstacktrace();
        }

        String response = client.getResponse();
         Log.i("MY INFO", response);
         GsonBuilder gsonb = new GsonBuilder();
         Gson gson = gsonb.create();
         Event pst = null;

        try {
            JSONObject j =new JSONObject(response);
            pst = gson.fromJson(j.toString(),  Event.class);

        } catch (JSONException e) {
            // Todo Auto-generated catch block
            e.printstacktrace();
        }

解决方法:

哎呀!我的坏我本来应该使用GET方法.这个url没有响应POST请求所以我得到了org.json.JSON异常:字符0的输入结束.因为这个我得到了null响应,它产生了异常.

android – 从url解析JSON,异常:解析数据时出错org.json.JSONException:字符115处的未终止数组

android – 从url解析JSON,异常:解析数据时出错org.json.JSONException:字符115处的未终止数组

我正在解析这个url,我有一个例外,不知道如何跳过它……我只需要获得100个最受欢迎的应用程序的名称.有一个关键的“im:name”,里面有一个键“lebel”,但是我认为它是无效的JsonArray,所以我需要找到通过键“im:name”获取名字的方法…有smb任何想法我该如何解决这个问题?

这是我的AsyncTask.class

    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    String jsonStringUrl = "https://itunes.apple.com/br/RSS/topfreeapplications/limit=100/json";
    JSONArray dataJsonArr = null;

    @Override
    protected void onPreExecute() {}

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

        try {
            // instantiate our json parser
            JsonParser jParser = new JsonParser();
            // get json string from url
            JSONObject json = jParser.getJSONFromUrl(jsonStringUrl);
            // get the array of users
//HERE I NEED TO CHANGE SOMETHING
            dataJsonArr = json.getJSONArray("Feed"); // probably wrong
            // loop through all users
            for (int i = 0; i < dataJsonArr.length(); i++) {
                JSONObject c = dataJsonArr.getJSONObject(i);
                // Storing each json item in variable
                String name = c.getString("im:name");//probably wrong
            }
        } catch (JSONException e) {
            e.printstacktrace();
        }
        return null;
    }
}

这是日志

    09-10 20:04:03.013  18211-18241/com.yuretsrodik.top100apps E/JsonParser.java﹕ Error parsing data org.json.JSONException: Unterminated array at character 115 of {"Feed":{"author":{"name":{"label":"iTunes Store"}, "uri":{"label":"http://www.apple.com/br/itunes/"}}, "entry":[n{"im:name":{"label":"Messenger"}, "im:image":[n{"label":"http://a474.phobos.apple.com/us/r30/Purple4/v4/78/1f/f9/781ff9ea-bf94-5309-4c32-4b901279e54a/mzl.rairyzma.53x53-50.png", "attributes":{"height":"53"}}, n{"label":"http://a990.phobos.apple.com/us/r30/Purple4/v4/78/1f/f9/781ff9ea-bf94-5309-4c32-4b901279e54a/mzl.rairyzma.75x75-65.png", "attributes":{"height":"75"}}, n{"label":"http://a1675.phobos.apple.com/us/r30/Purple4/v4/78/1f/f9/781ff9ea-bf94-5309-4c32-4b901279e54a/mzl.rairyzma.100x100-75.png", "attributes":{"height":"100"}}], "summary":{"label":"lcance instantaneamente as pessoas na sua vida, gratuitamente. O Messenger é como mensagens de texto, mas você não precisa pagar por cada mensagem (funciona com o seu plano de dados). \n\nNão é só para amigos no Facebook: envie mensagens para as pessoas na sua agenda de contatos e basta inserir um número de telefone para adicionar um novo contato.\n\nBate-papos em grupo: crie grupos para as pessoas a quem você mais envia mensagens. Dê um nome a eles, defina fotos para o grupo e os mantenha em um só lugar.\n\nFotos e vídeos: grave vídeos e tire selfies ou outras fotos diretamente do aplicativo e envie-os com um toque.\n\nLigações gratuitas: fale por quanto tempo quiser, mesmo com pessoas em outros países. (Ligações são gratuitas somente através do Wi-Fi. Do contrário, cobranças de dados padrão são aplicáveis).\n\nMais formas de enviar mensagens: \nDê vida às suas conversas com as figurinhas. \nVeja uma prévia das suas fotos e vídeos no rolo da câmera sem sair da conversa, e escolha as melhores para enviar.\nGrave mensagens de voz quando tiver mais para dizer\n\nRecursos adicionais:\nSaiba quando as pessoas viram suas mensagens.\nEncaminhe mensagens ou fotos para as pessoas que não estavam na conversa.\nProcure pessoas e grupos para entrar em contato com eles rapidamente.\nAtive a localização para que as pessoas saibam que você está nas imediações.\nVeja quem está disponível no Messenger e quem está on-line no Facebook. \nDesative as notificações quando você estiver trabalhando, dormindo ou se precisar dar um tempo.\nFique conectado para nunca perder uma mensagem."}, "im:price":{"label":"Grátis", "attributes":{"amount":"0.00000", "currency":"USD"}}, "im:contentType":{"attributes":{"term":"Application", "label":"Aplicativo"}}, "rights":{"label":"© Facebook, Inc."}, "title":{"label":"Messenger - Facebook, Inc."}, "link":{"attributes":{"rel":"alternate", "type":"text/html", "href":"https://itunes.apple.com/br/app/messenger/id454638411?mt=8&uo=2"}}, "id":{"label":"https://itunes.apple.com/br/app/messenger/id454638411?mt=8&uo=2", "attributes":{"im:id":"454638411", "im:bundleId":"com.facebook.Messenger"}}, "im:artist":{"label":"Facebook, Inc.", "attributes":{"href":"https://itunes.apple.com/br/artist/facebook-inc./id284882218?mt=8&uo=2"}}, "category":{"attributes":{"im:id":"6005", "term":"Social Networking", "scheme":"https://itunes.apple.com/br/genre/ios-redes-sociais/id6005?mt=8&uo=2", "label":"Redes sociais"}}, "im:releaseDate":{"label":"2011-10-19T15:39:30-07:00", "attributes":{"label":"19/10/2011"}}}, n{"im:name":{"label":"WhatsApp Messenger"}, "im:image":[n{"label":"http://a1554.phobos.apple.com/us/r30/Purple1/v4/1f/94/ff/1f94ffd9-159e-a247-2c0f-059f86b6c6c9/mzl.ivmblqpq.53x53-50.png", "attributes":{"height":"53"}}, n{"label":"http://a422.phobos.apple.com/us/r30/Purple1/v4/1f/94/ff/1f94ffd9-159e-a247-2c0f-059f86b6c6c9/mzl.ivmblqpq.75x75-65.png", "attributes":{"height":"75"}}, n{"label":"http://a1251.phobos.apple.com/us/r30/Purple1/v4/1f/94/ff/1f94ffd9-159e-a247-2c0f-059f86b6c6c9/mzl.ivmblqpq.100x100-75.png", "attributes":{"height":"100"}}], "summary":{"label":"O WhatsApp Messenger é um mensageiro para smartphone
09-10 20:04:03.013  18211-18241/com.yuretsrodik.top100apps W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x42044e48)
09-10 20:04:03.023  18211-18241/com.yuretsrodik.top100apps E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.yuretsrodik.top100apps, PID: 18211
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException
            at com.yuretsrodik.top100apps.AsyncTaskParseJson.doInBackground(AsyncTaskParseJson.java:32)
            at com.yuretsrodik.top100apps.AsyncTaskParseJson.doInBackground(AsyncTaskParseJson.java:10)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

将非常非常感谢帮助!!因为我真的堆叠(

解决方法:

首先,您进行调用将结果转换为名为json的字符串.
然后你必须将字符串转换为Json对象

          String json = null;  
        JSONObject jsonObj = null;  JSONObject FeedsObject = null;


     json = jParser.getJSONFromUrl(jsonStringUrl);
       if (json != null) {
    try {
         jsonObj = new JSONObject(json);

        FeedObject = jsonObj.getJSONObject("Feed");

为了更好地理解,请访问http://json.parser.online.fr/beta/并在那里粘贴您的json数据.
在右边你有一个设置按钮—>显示类型
您可以找到对象,字符串和数组

见下图.你试图获得一个不是数组的对象

android – 解析数据时出错org.json.JSONException:值<?xml的java.lang.String类型无法转换为JSONArray

android – 解析数据时出错org.json.JSONException:值<?xml的java.lang.String类型无法转换为JSONArray

我正在编写一个打算在 Android设备上运行的应用程序.应用程序通过PHP读取MysqL数据库中的信息,但是当我运行应用程序时,Log cat会提示错误’错误解析数据org.json.JSONException:Value

我得到的代码是从教程中下载的,请耐心等待我已经掌握了一些基本的PHP知识和很少的java知识.我已经测试了PHP脚本,它运行完美,所以我不会费心去附上它.

main.java代码:

 package test.an2MysqL;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.httpentity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;


public class main extends Activity {
/** Called when the activity is first created. */

   TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Create a crude view - this should really be set via the layout resources 
    // but since its an example saves declaring them in the XML. 
    LinearLayout rootLayout = new LinearLayout(getApplicationContext()); 
    txt = new TextView(getApplicationContext()); 
    rootLayout.addView(txt); 
    setContentView(rootLayout); 

    // Set the text and call the connect function. 
    txt.setText("Connecting...");
  //call the method to run the data retreival
    txt.setText(getServerData(KEY_121));



}
public static final String KEY_121 = "http://10.1.1.19/cms/test/android2MysqL/read.PHP"; //i use my real ip here



private String getServerData(String returnString) {

   InputStream is = null;

   String result = "";
    //the data to send
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("country","undefined"));

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            httpentity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e){
            Log.e("log_tag","Error in http connection "+e.toString());
    }

    //convert response to string
    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();
            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag","Error converting result "+e.toString());
    }
    //parse json data
    try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag","id: "+json_data.getInt("id")+
                            ",country: "+json_data.getString("country")+
                            ",documentn: "+json_data.getInt("documentn")
                    );
                    //Get an output to the screen
                    returnString += "\n\t" + jArray.getJSONObject(i);
       }
    }catch(JSONException e){
            Log.e("log_tag","Error parsing data "+e.toString());
    }
    return returnString;
}   

}

我很感激你能给我的任何帮助.

解决方法

正如您对问题的评论中所指出的那样,您的服务器似乎正在返回XML而不是JSON.您只需输出结果即可轻松确认:

}catch(JSONException e){
    Log.e("log_tag","Error parsing data "+e.toString());
    Log.e("log_tag","Failed data was:\n" + result);
}

如果它是XML,它几乎肯定是必须的,那么你需要让服务器输出JSON,或者你需要解析它发送给你的XML.

关于解析数据org.json.JSONException时出错:在字符0的输入结束json字符串解析出错的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于ajax请求json格式的数据,在经过interceptor时出现JSONException、android – org.json.JSON异常:字符0的输入结束、android – 从url解析JSON,异常:解析数据时出错org.json.JSONException:字符115处的未终止数组、android – 解析数据时出错org.json.JSONException:值<?xml的java.lang.String类型无法转换为JSONArray的相关知识,请在本站寻找。

本文标签: