【问题标题】:error. org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject错误。 org.json.JSONException:java.lang.String 类型的值 <br 无法转换为 JSONObject
【发布时间】:2015-04-14 05:34:09
【问题描述】:

我正在尝试从 android 活动将数据连接到我的 sqldatabase 进行注册页面,我收到此错误“org.json.JSONException: Value

我知道我在 SO 上看到了所有类似的问题。在过去的 7 个小时里,我厌倦了解决这个错误。我几乎尝试了所有方法,在网上搜索了很多,但无法找到解决此错误的方法:

Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject 

****JSONParser.java****

public class JSONParser {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

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

// constructor
public JSONParser() {
    StrictMode.setThreadPolicy(policy); 
}

public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    try {

        // check for request method
        if(method.equals("POST")){


            Log.d("my", "method equals POST is working");
            DefaultHttpClient httpClient = new DefaultHttpClient();

            Log.d("my", "HTTp client is working");
            HttpPost httpPost = new HttpPost(url);
            Log.d("my", "HTTp post is working");

            httpPost.setEntity(new UrlEncodedFormEntity(params));

            Log.d("my", "url encoded");

            HttpResponse httpResponse = httpClient.execute(httpPost);

            Log.d("my", "HTTp response is working");
            HttpEntity httpEntity = httpResponse.getEntity();

            Log.d("my", "HTTp entity is working");

            is = httpEntity.getContent();
            Log.d("my", "getcontent is working");


        }else if(method.equals("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);

        Log.d("my", "buffer reader crated");
        StringBuffer sb = new StringBuffer();


        Log.d("my", "string buffer object crated");
        String line = null;
        while ((line = reader.readLine())!= null) {
            sb.append(line + "\n");

            Log.d("my", "line appended");
        }
        is.close();
        Log.d("my", "inputstram closed");

        json = sb.toString();
        Log.d("my", "string buffer to string conversion");
    } 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;

}

}

TAP_Cliente_nuevo.java

enter code herepublic class Tap_Cliente_Nuevo 扩展 Activity {

JSONParser parseadorJson = new  JSONParser();
Button btn;
EditText RFC;
EditText Nombre;
EditText ApellidoP;
EditText ApellidoM;
EditText Telefono;
EditText Calle;
EditText Numero;
EditText Colonia;
EditText Municipio;
EditText Estado;
EditText CP;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tap__cliente__nuevo);
    RFC = (EditText)findViewById(R.id.txtRFCCliente);
    Nombre = (EditText)findViewById(R.id.txtNombreCliente);
    ApellidoP = (EditText)findViewById(R.id.txtApellidoPCliente);
    ApellidoM = (EditText)findViewById(R.id.txtApellidoMCliente);
    Telefono = (EditText)findViewById(R.id.txtTelefonoCliente);
    Calle = (EditText)findViewById(R.id.txtCalleCliente);
    Numero = (EditText)findViewById(R.id.txtNumeroCliente);
    Colonia = (EditText)findViewById(R.id.txtColoniaCliente);
    Municipio = (EditText)findViewById(R.id.txtMunicipioCliente);
    Estado = (EditText)findViewById(R.id.txtEstadoCliente);
    CP = (EditText)findViewById(R.id.txtCPCliente);

    btn = (Button)findViewById(R.id.btnRegistrarCliente);       
    btn.setOnClickListener(new OnClickListener() {          
        @Override
        public void onClick(View v) {

            if(RFC.getText().length()==0 ||
                    Nombre.getText().length()==0 ||
                    ApellidoP.getText().length()==0 ||
                    ApellidoM.getText().length()==0 ||
                    Telefono.getText().length()==0 ||
                    Calle.getText().length()==0 ||
                    Numero.getText().length()==0 ||
                    Colonia.getText().length()==0 ||
                    Municipio.getText().length()==0 ||
                    Estado.getText().length()==0 ||
                    CP.getText().length()==0){                  
                Toast.makeText(getApplicationContext(), "Por favor llena los campos obligatorios", Toast.LENGTH_SHORT).show();
        }else{
            List<NameValuePair> parametros = new ArrayList<NameValuePair>();
            parametros.add(new BasicNameValuePair("inRFC", RFC.getText().toString()));
            parametros.add(new BasicNameValuePair("inNombre", Nombre.getText().toString()));
            parametros.add(new BasicNameValuePair("inApPat", ApellidoP.getText().toString()));
            parametros.add(new BasicNameValuePair("inApMat", ApellidoM.getText().toString()));
            parametros.add(new BasicNameValuePair("inTel", Telefono.getText().toString()));
            parametros.add(new BasicNameValuePair("inCalle", Calle.getText().toString()));
            parametros.add(new BasicNameValuePair("inNum", Numero.getText().toString()));
            parametros.add(new BasicNameValuePair("inCol", Colonia.getText().toString()));
            parametros.add(new BasicNameValuePair("inMuni", Municipio.getText().toString()));
            parametros.add(new BasicNameValuePair("inEsta", Estado.getText().toString()));
            parametros.add(new BasicNameValuePair("inCP", CP.getText().toString()));


          Log.e("Registro", obtenIpServidor());

          parseadorJson.makeHttpRequest("http://192.168.1.72/tractofer/alta_clientes.php", "POST", parametros);
          Toast.makeText(getApplicationContext(), "Datos Insertados correctamente", Toast.LENGTH_SHORT).show();
            RFC.setText("");
            Nombre.setText("");
            ApellidoP.setText("");
            ApellidoM.setText("");
            Telefono.setText("");
            Calle.setText("");
            Numero.setText("");
            Colonia.setText("");
            Municipio.setText("");
            Estado.setText("");
            CP.setText("");
        }

        }
    });
}
public String obtenIpServidor()
{
    String ip=null;

    SharedPreferences pref = getSharedPreferences("com.example.tractopartesycamiones_preferences",MODE_PRIVATE);
    Log.e("Registro",  "tipo_conexion: " + pref.getString("tipo_conexion", "1"));

    if (pref.getString("tipo_conexion", "1").equals( "1"))
        ip="192.168.1.72";
    else
        ip = pref.getString("ip_servidor", "0.0.0.0");


    return ip;
}

}

alta_cliente.php

<?php
//Constantes

$db_usuario = "root";
$db_pass    = "";
$db_host    = "localhost";
$db_schema  = "tractofer";

//Conexion con la base de datos
$enlace = mysql_connect($db_host, $db_usuario, $db_pass)
    or die (' No se conecto al servidor');

mysql_select_db($db_schema,$enlace)
    or die('Error al seleccionar la base de datos');

$respuesta = array();
    $RFC = $_POST['inRFC'];
    $Nombre = $_POST['inNombre'];
    $ApPat = $_POST['inApPat'];
    $ApMat = $_POST['inApMat'];
    $Tel = $_POST['inTel'];
    $Calle = $_POST['inCalle'];
    $Num = $_POST['inNum'];
    $Col = $_POST['inCol'];
    $Muni = $_POST['inMuni'];
    $Esta = $_POST['inEsta'];
    $CP = $_POST['inCP'];

$db_query =
  "INSERT INTO cliente VALUES('$RFC', '$Nombre', '$ApPat', '$ApMat', '$Tel', '$Calle', '$Num', '$Col', '$Muni', '$Esta', '$CP')";
//Ejecutamos el Query
$resultado = mysql_query($db_query,$enlace)
    or die('Error en el query: ' .$db_query);

if($resultado)
{
$respuesta["success"]=1;
$respuesta["message"]="Usuario agregado";
    echo json_encode($respuesta);
}   
else
{ echo 'Error en el json'; }
//desconexion de la base de datos
@mysql_close($enlace);
?>

【问题讨论】:

    标签: java android json apache import


    【解决方案1】:

    在您的PHP 文件中,您正在使用echo 语句,该语句也作为响应输出。因此,您的 json 字符串包含一个 html 标记和/或行,因此无法解析。

    或者在您的 json 字符串中某处包含 &lt;br /&gt; 标记,因此无法解析。

    【讨论】:

    • Gracias amigo ya lo resolví, lo que pasa es que el php mandaba una advertencia de que los comando que estaba utilizando ya no estarían en futuras versiones del Wampserver me mandaba la tabla solo lo traslade a la nueva version你的清单。 Muchas gracias por 参赛者 :)
    猜你喜欢
    • 2016-12-20
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多