收到错误:错误分析数据org.json.JSONException:值< BR java.lang.String类型的,不能被转换为JSONObject的 [英] getting error :Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

查看:239
本文介绍了收到错误:错误分析数据org.json.JSONException:值< BR java.lang.String类型的,不能被转换为JSONObject的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的JSON解析器以下code。
我试图从ISO-8859-1改为UTF-8。
但我总是得到这个error.What我做错?
我无法弄清楚什么,我做错了。

 包com.iwantnew.www;
进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.util.List;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.client.utils.URLEn codedUtils;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.util.Log;公共类JSONParser {    静态InputStream为= NULL;
    静态的JSONObject jObj = NULL;
    静态JSON字符串=;    //构造
    公共JSONParser(){    }    //函数得到JSON的网址
    //通过HTTP POST或GET方法
    公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
            清单<&的NameValuePair GT; PARAMS){        //使HTTP请求
        尝试{            //检查请求的方法
            如果(方法==POST){
                //请求方法是POST
                // defaultHttpClient
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                HttpPost httpPost =新HttpPost(URL);
                httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));                HTT presponse HTT presponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();            }否则如果(方法==GET){
                //请求方法是GET
                DefaultHttpClient的HttpClient =新DefaultHttpClient();
                字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
                网址+ =? +中的paramString;
                HTTPGET HTTPGET =新HTTPGET(URL);                HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                HttpEntity httpEntity = HTT presponse.getEntity();
                是= httpEntity.getContent();
            }        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            e.printStackTrace();
        }赶上(IOException异常五){
            e.printStackTrace();
        }        尝试{
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                    是,ISO-8859-1),8);
            StringBuilder的SB =新的StringBuilder();
            串线= NULL;
            而((行= reader.readLine())!= NULL){
                sb.append(行+\\ n);
            }
            is.close();
            JSON = sb.toString();
        }赶上(例外五){
            Log.e(缓冲区错误,错误转换结果+ e.toString());
        }        //尝试分析字符串到一个JSON对象
        尝试{
            jObj =新的JSONObject(JSON);
        }赶上(JSONException E){
            Log.e(JSON解析器,错误分析数据+ e.toString());
        }        //返回JSON字符串
        返回jObj;    }
}

我用的MySQL的我的数据库。我是新与数据库到Android。帮助PLZ!
我的PHP文件看起来像这样:

 < PHP/ *
 *继code将创建一个新的产品行
 *所有产品的详细信息,从HTTP POST请求读
 * / 1//数组JSON响应
$响应=阵列();//检查必填字段
如果(使用isset($ _ POST ['量'])及和放大器;使用isset($ _ POST ['价格'])及和放大器;使用isset($ _ POST ['说明'])){    // $位置= $ _ POST ['位置'];
    $数量= $ _ POST ['量'];
    $价格= $ _ POST ['价格'];
    // $ =的productID $ _ POST ['区域'];
    $触点= $ _ POST ['接触'];
    $描述= $ _ POST ['说明'];    //其中包括DB连接类
    require_once __DIR__。 /db_connect.php';    //连接到数据库
    $ DB =新DB_CONNECT();    // MySQL的插入新行
    $结果= mysql_query(INSERT INTO room_tb(数量,价格,描述)VALUES('$数量,$价格,$描述'));
    // $ RESULT1 =的mysql_query(插入用户(userContactNumber)VALUES('$联系'));    //检查是否插入行或不
    如果(($结果)/ *放大器;及($ RESULT1)* /){
        //成功插入到数据库
        $响应[成功] = 1;
        $响应[消息] =房间添加成功。        //呼应JSON响应
        回声json_en code($响应);
    }其他{
        //没有插入一行
        $响应[成功] = 0;
        $响应[消息] =!哎呀发生错误。        //呼应JSON响应
        回声json_en code($响应);
    }
}其他{
    //必填字段缺失
    $响应[成功] = 0;
    $响应[消息] =必填字段(s)是失踪;    //呼应JSON响应
    回声json_en code($响应);
}
?>

我的Java文件看起来像this..i这里使用POST方法。

 包com.iwantnew.www;进口的java.util.ArrayList;
进口的java.util.List;进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;公共类post_item延伸活动{
    私人ProgressDialog pDialog;
    JSONParser jsonParser =新JSONParser();
    按钮add_room;
    的EditText contact_no;
    的EditText no_of_room;
    的EditText price_per_room;
    的EditText描述;    私人静态字符串url_create_product =htt​​p://10.0.2.2/android_iwant/android_add_room.php;    私有静态最后弦乐TAG_SUCCESS =成功;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.post_form);        // contact_no =(EditText上)findViewById(R.id.contact_no);
        no_of_room =(EditText上)findViewById(R.id.no_of_room);
        price_per_room =(EditText上)findViewById(R.id.price_per_room);
        说明=(EditText上)findViewById(R.id.description);        add_room =(按钮)findViewById(R.id.add_room);        add_room.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(视图v){
                //创建在后台线程的新产品
                新add_new_room()执行();
            }
        });
    }
//苏茹...
    类add_new_room扩展的AsyncTask<字符串,字符串,字符串> {        / **
         *启动后台线程显示进度对话框之前
         * * /
        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(post_item.this);
            pDialog.setMessage(保存细节..);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(真);
            pDialog.show();
        }        / **
         *创建产品
         * * /
        保护字符串doInBackground(字符串参数... args){
            //字符串触点= contact_no.getText()的toString()。
            串数量= no_of_room.getText()的toString()。
            串价格= price_per_room.getText()的toString()。
            字符串描述= description.getText()的toString()。            //大厦参数
            清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;();
            //params.add(new BasicNameValuePair(联系,联系));
            params.add(新BasicNameValuePair(量,数量));
            params.add(新BasicNameValuePair(价格,价格));
            params.add(新BasicNameValuePair(描述,描述));            //获取JSON对象
            //注意,创建产品网址接受POST方法
            JSONObject的JSON = jsonParser.makeHtt prequest(url_create_product,
                    POST,则params);            //检查日志猫来回响应
            Log.d(创建回应,json.toString());            //检查成功标记
            尝试{
                INT成功= json.getInt(TAG_SUCCESS);                如果(成功== 1){
                    //创建成功产品
                    意图I =新意图(getApplicationContext(),MainActivity.class);
                    startActivity(ⅰ);                    //关闭此屏幕
                    完();
                }其他{
                    //创建失败产品
                }
            }赶上(JSONException E){
                e.printStackTrace();
            }            返回null;
        }        / **
         *在完成后台任务之后辞退进度对话框
         * ** /
        保护无效onPostExecute(字符串FILE_URL){
            //辞退做一次对话
            pDialog.dismiss();
        }    }
}


解决方案

主要是你的错误是在那些行:

 如果(方法==POST){
 }否则如果(方法==GET)

在Java字符串比较有与等于 equalsIgnoreCase 的方法来进行。你的情况,InputStream的为空,而且从不被初始化。所以,你想一个空字符串,一个转换 StringBuilder.toString()正在恢复,到的JSONObject

编辑:

修改

 如果(方法==POST){
 }否则如果(方法==GET)

 如果(method.equalsIgnoreCase(POST)){
 //你的code
 }否则如果(method.equalsIgnoreCase(GET))
 //你的code

,看看它是否有什么差别(至少其误差应改变)

I have the following code in my json parser . I have tried changing from iso-8859-1 to utf-8. But i always get this error.What have i done wrong?? I could not figure it out of what i have done wrong.

package com.iwantnew.www;    
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 method
    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;

    }
}

I have used mysql for my database. I am new to android with database. help plz! My php file looks like this:

<?php

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

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

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

    //$location = $_POST['location'];
    $quantity = $_POST['quantity'];
    $price = $_POST['price'];
    //$productID = $_POST['area'];
    $contact = $_POST['contact'];
    $descriptions = $_POST['descriptions'];

    // 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 room_tb(quantity, price,description) VALUES('$quantity', '$price','$descriptions')");
    //$result1 = mysql_query("INSERT INTO users(userContactNumber) VALUES('$contact')");

    // check if row inserted or not
    if (($result)/*&& ($result1)*/) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Room added successfully.";

        // 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);
}
?>

MY java file look like this..i have used POST METHod here.

package com.iwantnew.www;

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 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;

public class post_item extends Activity {
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    Button add_room;
    EditText contact_no;
    EditText no_of_room;
    EditText price_per_room;
    EditText description;

    private static String url_create_product = "http://10.0.2.2/android_iwant/android_add_room.php";

    private static final String TAG_SUCCESS = "success";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.post_form);

        //contact_no = (EditText) findViewById(R.id.contact_no);
        no_of_room = (EditText) findViewById(R.id.no_of_room);
        price_per_room = (EditText) findViewById(R.id.price_per_room);
        description = (EditText) findViewById(R.id.description);

        add_room = (Button) findViewById(R.id.add_room);

        add_room.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // creating new product in background thread
                new add_new_room().execute();
            }
        });
    }
// suru...
    class add_new_room extends AsyncTask<String, String, String> {

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

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            //String contact = contact_no.getText().toString();
            String quantity = no_of_room.getText().toString();
            String price = price_per_room.getText().toString();
            String descriptions = description.getText().toString();

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

            // 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(), MainActivity.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();
        }

    }
}

解决方案

Mostly your mistake is in those lines:

if(method == "POST"){
 }else if(method == "GET")

String comparison in java has to be performed with the equals or equalsIgnoreCase method. In your case, the InputStream is is null, and it is never initialize. So you are trying to convert an empty string, the one the StringBuilder.toString() is returning, into a JSONObject.

Edit:

Change

if(method == "POST"){
 }else if(method == "GET")

with

if(method.equalsIgnoreCase("POST")){
 // your code
 }else if(method.equalsIgnoreCase("GET"))
 // your code

and see if it makes any difference (at least the error should change)

这篇关于收到错误:错误分析数据org.json.JSONException:值&LT; BR java.lang.String类型的,不能被转换为JSONObject的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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