值小于,java.lang.String类型BR无法转换为JSONObject的android上 [英] Value <br of type java.lang.String cannot be converted to JSONObject on android

查看:331
本文介绍了值小于,java.lang.String类型BR无法转换为JSONObject的android上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的Java code和我收到的问题在此:W / System.err的(1362):org.json.JSONException:值

 公共类主要扩展活动{

    //标签显示GCM消息
    TextView的lblMessage;
    控制器aController;


    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        / ******************* Intialize数据库************* /
        DBAdapter.init(本);

        //获取全球控制Class对象
        //(见在AndroidManifest.xml中应用标签)
        aController =(控制器)getApplicationContext();


        //检查网络present
        如果(!aController.isConnectingToInternet()){

            // Internet连接没有present
            aController.showAlertDialog(Main.this,
                    Internet连接错误,
                    请连接到Internet连接,假);
            //停止执行返回code
            返回;
        }

        //检查设备包含在SQLite数据库,或不能自我信息。
        INT vDevice = DBAdapter.validateDevice();

        如果(vDevice大于0)
        {

            //启动主要活动
            意图I =新的意图(getApplicationContext(),GridViewExample.class);
            startActivity(ⅰ);
            完();
        }
        其他
        {
            字符串deviceIMEI =;
            如果(Config.SECOND_SIMULATOR){

                //如果你想开第二simutor使它在CONFIG真
                //进行实际测试,我们使用IMEI号保存唯一的设备

                deviceIMEI =0000000000000000;
            }
            其他
            {
              //获取IMEI号码
             TelephonyManager tManager =(TelephonyManager)getBaseContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
              deviceIMEI = tManager.getDeviceId();
            }

            / *******验证设备从服务器****** /
            // Web服务器请求的URL
            字符串serverURL使用= Config.YOUR_SERVER_URL +validate_device.php;

            //使用AsyncTask的Execute方法prevent ANR问题
            LongOperation serverRequest =新LongOperation();

            serverRequest.execute(serverURL使用,deviceIMEI,,);

        }

    }


    //使用类扩展的AsyncTask类
    公共类LongOperation扩展的AsyncTask<字符串,太虚,字符串> {

            //所需的初始化

           //私人最终的HttpClient客户端=新DefaultHttpClient();
           //专用控制器aController = NULL;
            私人字符串错误= NULL;
            私人ProgressDialog对话框=新ProgressDialog(Main.this);
            字符串数据=;
            INT sizeData = 0;


            在preExecute保护无效(){
                //注意:您可以拨打UI元素在这里。

                //启动进度对话框(消息)

                Dialog.setMessage(验证设备。);
                Dialog.show();

            }

            后//调用上preExecute方法
            保护字符串doInBackground(字符串... PARAMS){

                / ************使邮政呼叫到Web服务器*********** /
                BufferedReader中读= NULL;
                字符串内容=;
                     //发送数据
                    尝试{

                        //定义URL,其​​中发送数据
                           网址URL =新的URL(PARAMS [0]);

                        //设置请求参数
                        如果(!PARAMS [1] .equals())
                           数据+ =与& + URLEn coder.en code(数据1,UTF-8)+=+参数[1]的ToString();
                        如果(!PARAMS [2] .equals())
                               数据+ =与& + URLEn coder.en code(数据2,UTF-8)+=+参数[2]的ToString();
                        如果(!PARAMS [3] .equals())
                               数据+ =与& + URLEn coder.en code(数据3,UTF-8)+=+参数[3]的ToString();
                      Log.i(GCM,数据);

                      //发送POST数据请求

                      URLConnection的康恩= url.openConnection();
                      conn.setDoOutput(真正的);
                      OutputStreamWriter WR =新OutputStreamWriter(conn.getOutputStream());
                      wr.write(数据);
                      wr.flush();

                      //获取服务器响应

                      读者=新的BufferedReader(新的InputStreamReader(conn.getInputStream()));
                      StringBuilder的SB =新的StringBuilder();
                      串线= NULL;

                        //读取服务器响应
                        而((行= reader.readLine())!= NULL)
                            {
                                   //将字符串中的服务器响应
                                   sb.append(行+\ N);
                            }

                        //追加服务器响应为内容字符串
                       含量= sb.toString();
                    }
                    赶上(例外前)
                    {
                        错误= ex.getMessage();
                    }
                    最后
                    {
                        尝试
                        {

                            reader.close();
                        }

                        赶上(例外前){}
                    }

                / ******************* **** /
                返回的内容;
            }

            保护无效onPostExecute(字符串内容){
                //注意:您可以拨打UI元素在这里。

                //关闭进度对话框
                Dialog.dismiss();

                如果(错误!= NULL){


                } 其他 {

                    //显示响应的Json屏幕(活动)

                 / ******************开始解析响应JSON数据************* /
                    aController.clearUserData();

                    的JSONObject jsonResponse;

                    尝试 {

                         / ******创建一个新的JSONObject从JSON字符串名称/值映射。 ******** /
                         jsonResponse =新的JSONObject的(内容);

                         / *****返回通过名称映射,如果它存在,并且是一个JSONArray值。 *** /
                         / *******否则返回null。 ******* /
                         JSONArray jsonMainNode = jsonResponse.optJSONArray(机器人);

                         / ***********流程各节点的JSON ************ /

                         INT lengthJsonArr = jsonMainNode.length();

                         的for(int i = 0; I< lengthJsonArr;我++)
                         {
                             / ******查看对象的每个JSON节点。*********** /
                             的JSONObject jsonChildNode = jsonMainNode.getJSONObject(ⅰ);

                             / *******获取节点值********** /
                             字符串状态= jsonChildNode.optString(身份)的toString()。

                             Log.i(GCM, - +状态);

                             //如果服务器响应状态更新
                             如果(Status.equals(更新)){

                                。字符串REGID = jsonChildNode.optString(REGID)的toString();
                                字符串名称= jsonChildNode.optString(姓名)的toString()。
                                字符串email = jsonChildNode.optString(电子邮件)的toString()。
                                IMEI串= jsonChildNode.optString(IMEI)的toString()。

                               //在SQLite数据库添加设备自身的数据
                                DBAdapter.addDeviceData(姓名,电子邮件,REGID,IMEI);

                                //启动GridViewExample活动
                                意图I1 =新的意图(getApplicationContext(),GridViewExample.class);
                                startActivity(I1);
                                完();

                                Log.i(GCM, - +姓名);
                             }
                             否则,如果(Status.equals(安装)){

                                 //启动RegisterActivity活动
                                意图I1 =新的意图(getApplicationContext(),RegisterActivity.class);
                                startActivity(I1);
                                完();

                             }


                        }

                     / ******************结束解析响应JSON数据************* /


                     }赶上(JSONException E){

                         e.printStackTrace();
                     }


                 }
            }

        }




    @覆盖
    保护无效的onDestroy(){

        super.onDestroy();
    }

}
 

PHP code:我已经在this.suggest我用一个数组,为什么类型不匹配存在的

 < PHP

 require_once('loader.php');

 $ IMEI = $ _REQUEST ['DATA1'];
 $ REGID = $ _REQUEST ['数据2'];

// $ resultUsers = getRegIDUser($ REGID);
$ resultUsers = getIMEIUser($ IMEI);

如果($ resultUsers!= FALSE)
    $ NumOfUsers = mysql_num_rows($ resultUsers);
其他
    $ NumOfUsers = 0;

$ jsonData =阵列();

如果($ NumOfUsers大于0){

 而($ rowUsers = mysql_fetch_array($ resultUsers)){


    $ jsonTempData =阵列();

    $ jsonTempData ['REGID'] = $ rowUsers [gcm_regid];
    $ jsonTempData ['名称'] = $ rowUsers [名称];
    $ jsonTempData [电子邮件] = $ rowUsers [电子邮件];
    $ jsonTempData ['IMEI'] = $ rowUsers [IMEI];
    $ jsonTempData ['状态'] =升级;

    $ jsonData [] = $ jsonTempData;

   }
}
其他{

    $ jsonTempData =阵列();

    $ jsonTempData ['REGID'] =;
    $ jsonTempData ['名称'] =;
    $ jsonTempData [电子邮件] =;
    $ jsonTempData ['IMEI'] =;
    $ jsonTempData ['状态'] =安装;

    $ jsonData [] = $ jsonTempData;

}

$ outputArr =阵列();
$ outputArr ['机器人'] = $ jsonData;

// EN code数组到JSON数据
的print_r(json_en code($ outputArr));

?>
 

让问题.... !!

下面是关于异常的细节。

 十二月四号至16日:54:57.876:W / System.err的(1603):org.json.JSONException:值小于; BR java.lang.String类型不能转换到的JSONObject
12月4号至16日:54:57.916:W / System.err的(1603):在org.json.JSON.typeMismatch(JSON.java:111)
12月4号至16日:54:57.916:W / System.err的1603:在org.json.JSONObject< INIT>(JSONObject.java:158)
12月4号至16日:54:57.916:W / System.err的(1603):在org.json.JSONObject< INIT>(JSONObject.java:171)
12月4号至16日:54:57.916:W / System.err的(1603):在com.androidexample.mobilegcm.Main $ LongOperation.onPostExecute(Main.java:213)
12月4号至16日:54:57.926:W / System.err的1603:在com.androidexample.mobilegcm.Main $ LongOperation.onPostExecute(Main.java:1)
12月4号至16日:54:57.926:W / System.err的(1603):在android.os.AsyncTask.finish(AsyncTask.java:631)
12月4号至16日:54:57.946:W / System.err的(1603):在android.os.AsyncTask.access $ 600(AsyncTask.java:177)
12月4号至16日:54:57.976:W / System.err的1603:在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:644)
12月4号至16日:54:57.976:W / System.err的(1603):在android.os.Handler.dispatchMessage(Handler.java:99)
12月4号至16日:54:57.976:W / System.err的(1603):在android.os.Looper.loop(Looper.java:137)
12月4号至16日:54:58.007:W / System.err的(1603):在android.app.ActivityThread.main(ActivityThread.java:5041)
12月4号至16日:54:58.007:W / System.err的1603:在java.lang.reflect.Method.invokeNative(本机方法)
12月4号至16日:54:58.016:W / System.err的(1603):在java.lang.reflect.Method.invoke(Method.java:511)
12月4号至16日:54:58.026:W / System.err的(1603):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
12月4号至16日:54:58.036:W / System.err的(1603):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12月4号至16日:54:58.036:W / System.err的(1603):在dalvik.system.NativeStart.main(本机方法)
 

这就是所有的内容都返回.....日志...

  04-16 15:50:​​10.575:I /返回(1579):其中; BR />
04-16 15:50:​​10.575:I /返回(1579):其中,字体大小='1'><表类='Xdebug的错误XE-通知DIR ='升'的边界='1'CELLSPACING ='0'CELLPADDING ='1'>
04-16 15:50:​​10.575:I /返回(1579):其中,TR>百分位ALIGN =左BGCOLOR =#f57900合并单元格=5><跨度风格=背景颜色:#CC0000;颜色:#fce94f;字体大小:X-大;'>< / SPAN>(!)注意:未定义指数:数据2在C:\瓦帕\的www \ gcm_server_files \ validate_device.php上线474; I> 6< / I>< /第i;< / TR>
04-16 15:50:​​10.575:I /返回(1579):其中,TR>百分位ALIGN =左BGCOLOR =#e9b96e合并单元格=5>调用堆栈和LT; /第i;< / TR>
04-16 15:50:​​10.575:I /返回(1579):其中,TR>百分位ALIGN =中心BGCOLOR =#eeeeec'>#< /第i个百分位ALIGN =左 BGCOLOR =#eeeeec'>时间< /第i个百分位ALIGN =左BGCOLOR =#eeeeec'>内存< /第i个百分位ALIGN =左BGCOLOR =#eeeeec'>功能与LT; /第i个百分位ALIGN =左BGCOLOR =#eeeeec'>位置和LT; /第i;< / TR>
04-16 15:50:​​10.575:I /返回(1579):其中,TR>< TD BGCOLOR ='#eeeeec'ALIGN ='中心'> 1< / TD>< TD BGCOLOR ='#eeeeec ALIGN ='中心'> 0.0193< / TD>< TD BGCOLOR ='#eeeeec'ALIGN ='正确的'> 145240< / TD>< TD BGCOLOR ='#eeeeec'> {主}() < / TD>< TD标题=C:\瓦帕\的www \ gcm_server_files \ validate_device.php'BGCOLOR =#eeeeec'> .. \ validate_device.php< B>:< / B> 0℃/ TD>< / TR>
04-16 15:50:​​10.575的:I /返回(1579):其中; /表>&所述; /字体>
04-16 15:50:​​10.575:I /返回(1579):{机器人:[{REGID:,名:,电子邮件:,IMEI: 状态:安装}]}
 

还是起...返回的HTML code..i这么多的一部分,只需要code部分来自{机器人},即最后一行只有..

  04-16 16:17:49.925:W / System.err的(4958):org.json.JSONException:预期:后的主要人品6 {}主力( )< / TD>< TD标题=C:\瓦帕\的www \ gcm_server_files \ validate_device.php'BGCOLOR =#eeeeec'> .. \ validate_device.php< B>:< / B> 0℃ / TD>&所述; / TR>
04-16 16:17:49.925:W / System.err的(4958):其中; /表>&所述; /字体>
04-16 16:17:49.925:W / System.err的(4958):{机器人:[{REGID:,名:,电子邮件:,IMEI: ,状态:安装}]}
 

解决方案

关于你的HTML

您正试图摆脱一些HTML code,实际上告诉你有一个错误。这里是什么样子:

也许如果你解决这个问题,你的JSON的问题就会消失在自己,因为你的JSON之前不会有HTML的东西。


响应

早期部分

我想你是在这条线让你的异常(请告诉我,如果我错了):

  jsonResponse =新的JSONObject的(内容);
 

如果你想知道什么是错的内容解析,您可能要登录该字符串,看看它的外观。

显然,内容是HTML code(它包含了一些< BR ,根据异常),而不是一个适当的JSON字符串。看看你在哪里得到这个字符串的,这可能是你的问题。


更新:

确定,根据您所发布的是什么,你的内容字符串包含JSON字符串(一个用括号括起来 {} ),但它也包含一个HTML部分,这需要除去。

将这个code,然后再尝试创建的JSONObject

  INT jsonStart = Content.indexOf({);
INT jsonEnd = Content.lastIndexOf(});

如果(jsonStart> = 0&安培;&安培; jsonEnd> = 0&安培;&安培; jsonEnd> jsonStart){
    含量= Content.substring(jsonStart,jsonEnd + 1);
} 其他 {
    //处理的情况下JSON内容在这里
}
 


更新2:

在previous code段似乎并不足够,因为您的HTML包含括号( {} )。如果服务器始终返回类型的HTML,你可能只想摆脱字体标记的运行previous段之前:

 内容= Content.replaceFirst(<字体> *<?/ FONT>中,);
 

警告:这是非常粗略的,而答案只有这个非常特殊的问题。它不会与每一个可能的服务器响应工作。

您应该看一看就从Java中的字符串去除HTML等问题,更完整的答案。

This is my java code and i am getting problem in this: W/System.err(1362): org.json.JSONException: Value

public class Main extends Activity {

    // label to display gcm messages
    TextView lblMessage;
    Controller aController;


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

        /******************* Intialize Database *************/
        DBAdapter.init(this);

        // Get Global Controller Class object 
        // (see application tag in AndroidManifest.xml)
        aController = (Controller) getApplicationContext();


        // Check if Internet present
        if (!aController.isConnectingToInternet()) {

            // Internet Connection is not present
            aController.showAlertDialog(Main.this,
                    "Internet Connection Error",
                    "Please connect to Internet connection", false);
            // stop executing code by return
            return;
        }

        //Check device contains self information in sqlite database or not. 
        int vDevice = DBAdapter.validateDevice();   

        if(vDevice > 0)
        {   

            // Launch Main Activity
            Intent i = new Intent(getApplicationContext(), GridViewExample.class);
            startActivity(i);
            finish();
        }
        else
        {
            String deviceIMEI = "";
            if(Config.SECOND_SIMULATOR){

                //Make it true in CONFIG if you want to open second simutor
                // for testing actually we are using IMEI number to save a unique device

                deviceIMEI = "000000000000000";
            }   
            else
            {
              // GET IMEI NUMBER      
             TelephonyManager tManager = (TelephonyManager) getBaseContext()
                .getSystemService(Context.TELEPHONY_SERVICE);
              deviceIMEI = tManager.getDeviceId(); 
            }

            /******* Validate device from server ******/
            // WebServer Request URL
            String serverURL = Config.YOUR_SERVER_URL+"validate_device.php";

            // Use AsyncTask execute Method To Prevent ANR Problem
            LongOperation serverRequest = new LongOperation(); 

            serverRequest.execute(serverURL,deviceIMEI,"","");

        }   

    }       


    // Class with extends AsyncTask class
    public class LongOperation  extends AsyncTask<String, Void, String> {

            // Required initialization

           //private final HttpClient Client = new DefaultHttpClient();
           // private Controller aController = null;
            private String Error = null;
            private ProgressDialog Dialog = new ProgressDialog(Main.this); 
            String data =""; 
            int sizeData = 0;  


            protected void onPreExecute() {
                // NOTE: You can call UI Element here.

                //Start Progress Dialog (Message)

                Dialog.setMessage("Validating Device..");
                Dialog.show();

            }

            // Call after onPreExecute method
            protected String doInBackground(String... params) {

                /************ Make Post Call To Web Server ***********/
                BufferedReader reader=null;
                String Content = "";
                     // Send data 
                    try{

                        // Defined URL  where to send data
                           URL url = new URL(params[0]);

                        // Set Request parameter
                        if(!params[1].equals(""))
                           data +="&" + URLEncoder.encode("data1", "UTF-8") + "="+params[1].toString();
                        if(!params[2].equals(""))
                               data +="&" + URLEncoder.encode("data2", "UTF-8") + "="+params[2].toString(); 
                        if(!params[3].equals(""))
                               data +="&" + URLEncoder.encode("data3", "UTF-8") + "="+params[3].toString();
                      Log.i("GCM",data);

                      // Send POST data request

                      URLConnection conn = url.openConnection(); 
                      conn.setDoOutput(true); 
                      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
                      wr.write( data ); 
                      wr.flush(); 

                      // Get the server response 

                      reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                      StringBuilder sb = new StringBuilder();
                      String line = null;

                        // Read Server Response
                        while((line = reader.readLine()) != null)
                            {
                                   // Append server response in string
                                   sb.append(line + "\n");
                            }

                        // Append Server Response To Content String 
                       Content = sb.toString();
                    }
                    catch(Exception ex)
                    {
                        Error = ex.getMessage();
                    }
                    finally
                    {
                        try
                        {

                            reader.close();
                        }

                        catch(Exception ex) {}
                    }

                /*****************************************************/
                return Content;
            }

            protected void onPostExecute(String Content) {
                // NOTE: You can call UI Element here.

                // Close progress dialog
                Dialog.dismiss();

                if (Error != null) {


                } else {

                    // Show Response Json On Screen (activity)

                 /****************** Start Parse Response JSON Data *************/
                    aController.clearUserData();

                    JSONObject jsonResponse;

                    try {

                         /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                         jsonResponse = new JSONObject(Content);

                         /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                         /*******  Returns null otherwise.  *******/
                         JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");

                         /*********** Process each JSON Node ************/

                         int lengthJsonArr = jsonMainNode.length();  

                         for(int i=0; i < lengthJsonArr; i++) 
                         {
                             /****** Get Object for each JSON node.***********/
                             JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                             /******* Fetch node values **********/
                             String Status = jsonChildNode.optString("status").toString();

                             Log.i("GCM","---"+Status);

                             // IF server response status is update
                             if(Status.equals("update")){

                                String RegID      = jsonChildNode.optString("regid").toString();
                                String Name       = jsonChildNode.optString("name").toString();
                                String Email      = jsonChildNode.optString("email").toString();
                                String IMEI       = jsonChildNode.optString("imei").toString();

                               // add device self data in sqlite database
                                DBAdapter.addDeviceData(Name, Email,RegID, IMEI);

                                // Launch GridViewExample Activity
                                Intent i1 = new Intent(getApplicationContext(), GridViewExample.class);
                                startActivity(i1);
                                finish();

                                Log.i("GCM","---"+Name);
                             }
                             else if(Status.equals("install")){  

                                 // Launch RegisterActivity Activity
                                Intent i1 = new Intent(getApplicationContext(), RegisterActivity.class);
                                startActivity(i1);
                                finish();

                             }


                        }

                     /****************** End Parse Response JSON Data *************/     


                     } catch (JSONException e) {

                         e.printStackTrace();
                     }


                 }
            }

        }




    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

}

PHP code:i have used a array in this.suggest me why type mismatch occuring

<?php

 require_once('loader.php');

 $imei     = $_REQUEST['data1'];
 $regID    = $_REQUEST['data2'];

//$resultUsers =  getRegIDUser($regID);
$resultUsers =  getIMEIUser($imei);

if ($resultUsers != false)
    $NumOfUsers = mysql_num_rows($resultUsers);
else
    $NumOfUsers = 0;

$jsonData      = array();

if ($NumOfUsers > 0) {

 while ($rowUsers = mysql_fetch_array($resultUsers)) {


    $jsonTempData = array(); 

    $jsonTempData['regid']        = $rowUsers["gcm_regid"];
    $jsonTempData['name']         = $rowUsers["name"];
    $jsonTempData['email']        = $rowUsers["email"];
    $jsonTempData['imei']         = $rowUsers["imei"];
    $jsonTempData['status']       = "update";

    $jsonData[] = $jsonTempData;

   }
}
else{

    $jsonTempData = array();

    $jsonTempData['regid']        = "";
    $jsonTempData['name']         = "";
    $jsonTempData['email']        = "";
    $jsonTempData['imei']         = "";
    $jsonTempData['status']       = "install";

    $jsonData[] = $jsonTempData;

}

$outputArr = array();
$outputArr['Android'] = $jsonData;    

// Encode Array To JSON Data
print_r( json_encode($outputArr));

?>

getting problems....!!

Here are the details regarding exception..

04-16 12:54:57.876: W/System.err(1603): org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
04-16 12:54:57.916: W/System.err(1603):     at org.json.JSON.typeMismatch(JSON.java:111)
04-16 12:54:57.916: W/System.err(1603):     at org.json.JSONObject.<init>(JSONObject.java:158)
04-16 12:54:57.916: W/System.err(1603):     at org.json.JSONObject.<init>(JSONObject.java:171)
04-16 12:54:57.916: W/System.err(1603):     at com.androidexample.mobilegcm.Main$LongOperation.onPostExecute(Main.java:213)
04-16 12:54:57.926: W/System.err(1603):     at com.androidexample.mobilegcm.Main$LongOperation.onPostExecute(Main.java:1)
04-16 12:54:57.926: W/System.err(1603):     at android.os.AsyncTask.finish(AsyncTask.java:631)
04-16 12:54:57.946: W/System.err(1603):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-16 12:54:57.976: W/System.err(1603):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-16 12:54:57.976: W/System.err(1603):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 12:54:57.976: W/System.err(1603):     at android.os.Looper.loop(Looper.java:137)
04-16 12:54:58.007: W/System.err(1603):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-16 12:54:58.007: W/System.err(1603):     at java.lang.reflect.Method.invokeNative(Native Method)
04-16 12:54:58.016: W/System.err(1603):     at java.lang.reflect.Method.invoke(Method.java:511)
04-16 12:54:58.026: W/System.err(1603):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-16 12:54:58.036: W/System.err(1603):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-16 12:54:58.036: W/System.err(1603):     at dalvik.system.NativeStart.main(Native Method)

This is the all content is returning.....in log...

04-16 15:50:10.575: I/returning(1579): <br />
04-16 15:50:10.575: I/returning(1579): <font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
04-16 15:50:10.575: I/returning(1579): <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: data2 in C:\wamp\www\gcm_server_files\validate_device.php on line <i>6</i></th></tr>
04-16 15:50:10.575: I/returning(1579): <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
04-16 15:50:10.575: I/returning(1579): <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
04-16 15:50:10.575: I/returning(1579): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0193</td><td bgcolor='#eeeeec' align='right'>145240</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\gcm_server_files\validate_device.php' bgcolor='#eeeeec'>..\validate_device.php<b>:</b>0</td></tr>
04-16 15:50:10.575: I/returning(1579): </table></font>
04-16 15:50:10.575: I/returning(1579): {"Android":[{"regid":"","name":"","email":"","imei":"","status":"install"}]}

still returning this much part of html code..i need only code part from {"Android"} onwards...i.e the last line only..

04-16 16:17:49.925: W/System.err(4958): org.json.JSONException: Expected ':' after main at character 6 of {main}(  )</td><td title='C:\wamp\www\gcm_server_files\validate_device.php' bgcolor='#eeeeec'>..\validate_device.php<b>:</b>0</td></tr>
04-16 16:17:49.925: W/System.err(4958): </table></font>
04-16 16:17:49.925: W/System.err(4958): {"Android":[{"regid":"","name":"","email":"","imei":"","status":"install"}]}

解决方案

About your HTML

You're trying to get rid of some HTML code that actually tells you there is an error. Here is what it looks like:

Maybe if you solve that problem, your JSON issue will vanish on its own, because you won't have HTML stuff before your JSON.


Earlier part of the response

I guess you are getting your exception at this line (please tell me if I'm wrong):

jsonResponse = new JSONObject(Content);

If you want to know what's wrong with the parsing of Content, you might want to log that string and see how it looks.

Apparently, Content is HTML code (It contains some <br, according to the exception) instead of a proper JSON String. Take a look at where you get this string from, this is probably your problem.


UPDATE:

OK, according to what you posted, your Content string contains the JSON string (the one surrounded by braces {}) but it also contains an HTML part, which needs to be removed.

Put this code before you try to create the JSONObject:

int jsonStart = Content.indexOf("{");
int jsonEnd = Content.lastIndexOf("}");

if (jsonStart >= 0 && jsonEnd >= 0 && jsonEnd > jsonStart) {
    Content = Content.substring(jsonStart, jsonEnd + 1);
} else {
    // deal with the absence of JSON content here
}


UPDATE 2:

The previous code snippet does not seem sufficient because your HTML contains braces ({}). If the server always returns that kind of HTML, you might want to just get rid of the font tag before running the previous snippet:

Content = Content.replaceFirst("<font>.*?</font>", "");

WARNING: This is very sketchy, and answers only this very particular issue. It won't work with every possible server response.

You should have a look at other questions regarding the removal of HTML from a String in Java, for more complete answers.

这篇关于值小于,java.lang.String类型BR无法转换为JSONObject的android上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆