Android JSONException:无法将 java.lang.String 类型的值转换为 JSONObject

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10267910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:04:04  来源:igfitidea点击:

JSONException: Value of type java.lang.String cannot be converted to JSONObject

androidjsonparsing

提问by RCK69

I have a JSON file with 2 JSON-Arrays in it: One Array for routes and one Array for sights.

我有一个 JSON 文件,其中包含 2 个 JSON 数组:一个数组用于路线,一个数组用于景点。

A route should consist of several sights where the user gets navigated to. Unfortunately I am getting the error:

一条路线应该由用户导航到的几个景点组成。不幸的是我收到错误:

JSONException: Value of type java.lang.String cannot be converted to JSONObject

JSONException:无法将 java.lang.String 类型的值转换为 JSONObject

Here are my variables and the code that parses the JSON-File:

这是我的变量和解析 JSON 文件的代码:

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

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();
    // hier habe ich das JSON-File als String
    json = sb.toString();
    Log.i("JSON Parser", 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;
}

Log.i("JSON Parser", json); shows me that at the beginning of the generated string there is a strange sign: enter image description here

Log.i("JSON 解析器", json); 告诉我在生成的字符串的开头有一个奇怪的符号:在此处输入图片说明

but the error happens here:

但错误发生在这里:

try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

04-22 14:01:05.043: E/JSON Parser(5868): Error parsing data org.json.JSONException: Value //STRANGE SIGN HERE // of type java.lang.String cannot be converted to JSONObject

04-22 14:01:05.043: E/JSON Parser(5868): 解析数据时出错 org.json.JSONException: Value //STRANGE SIGN HERE // 类型 java.lang.String 无法转换为 JSONObject

anybody has a clue on how to get rid of these signs in order to create the JSONObject?

任何人都有关于如何摆脱这些标志以创建 JSONObject 的线索?

采纳答案by Zaz Gmy

see this http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-

看到这个 http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-

JSONObject

JSON对象

public JSONObject(java.lang.String source)
           throws JSONException

Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.

从源 JSON 文本字符串构造一个 JSONObject。这是最常用的`JSONObject 构造函数。

Parameters:
    source - `A string beginning with { (left brace) and ending with } (right brace).` 
Throws:
    JSONException - If there is a syntax error in the source string or a duplicated key.

you try to use some thing like:

您尝试使用以下内容:

new JSONObject("{your string}")

回答by khaintt

Reason is some un-wanted characters was added when you compose the String. The temp solution is

原因是在编写字符串时添加了一些不需要的字符。临时解决方案是

return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));

But try to remove hidden characters on source String.

但是尝试删除源字符串上的隐藏字符。

回答by MTurPash

Had the same problem for few days. Found a solution at last. The PHP server returned some unseen characters which you could not see in the LOG or in System.out.

有同样的问题几天了。终于找到解决办法了。PHP 服务器返回了一些您在 LOG 或 System.out 中看不到的看不见的字符。

So the solution was that i tried to substring my json String one by one and when i came to substring(3) the error went away.

所以解决方案是我尝试将我的 json String 一个一个地子串起来,当我来到 substring(3) 时,错误消失了。

BTW. i used UTF-8 encoding on both sides. PHP side: header('Content-type=application/json; charset=utf-8');

顺便提一句。我在两边都使用了 UTF-8 编码。PHP端:header('Content-type=application/json; charset=utf-8');

JAVA side: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

JAVA方面: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

So try the solution one by one 1,2,3,4...! Hope it helps you guys!

所以一一尝试解决方案 1,2,3,4...!希望对大家有帮助!

try {
            jObj = new JSONObject(json.substring(3));
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
        }

回答by izbrannick

Here is UTF-8 version, with several exception handling:

这是 UTF-8 版本,有几个异常处理:

static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
static HttpResponse httpResponse = null;

public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(params, true);
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        HttpGet httpPost = new HttpGet( url);
        httpResponse = httpClient.execute( httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           
    } catch (UnsupportedEncodingException ee) {
        Log.i("UnsupportedEncodingException...", is.toString());
    } catch (ClientProtocolException e) {
        Log.i("ClientProtocolException...", is.toString());
    } catch (IOException e) {
        Log.i("IOException...", is.toString());
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8); //old charset iso-8859-1
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        reader.close();
        json = sb.toString();
        Log.i("StringBuilder...", 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 (Exception e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
        try {
            jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
        } catch (Exception e0) {
            Log.e("JSON Parser0", "Error parsing data [" + e0.getMessage()+"] "+json);
            Log.e("JSON Parser0", "Error parsing data " + e0.toString());
            try {
                jObj = new JSONObject(json.substring(1));
            } catch (Exception e1) {
                Log.e("JSON Parser1", "Error parsing data [" + e1.getMessage()+"] "+json);
                Log.e("JSON Parser1", "Error parsing data " + e1.toString());
                try {
                    jObj = new JSONObject(json.substring(2));
                } catch (Exception e2) {
                    Log.e("JSON Parser2", "Error parsing data [" + e2.getMessage()+"] "+json);
                    Log.e("JSON Parser2", "Error parsing data " + e2.toString());
                    try {
                        jObj = new JSONObject(json.substring(3));
                    } catch (Exception e3) {
                        Log.e("JSON Parser3", "Error parsing data [" + e3.getMessage()+"] "+json);
                        Log.e("JSON Parser3", "Error parsing data " + e3.toString());
                    }
                }
            }
        }
    }

    // return JSON String
    return jObj;

}

回答by Mustafa Ferhan

This is simple way (thanks Gson)

这是简单的方法(感谢 Gson)

JsonParser parser = new JsonParser();
String retVal = parser.parse(param).getAsString();

https://gist.github.com/MustafaFerhan/25906d2be6ca109f61ce#file-evaluatejavascript-string-problem

https://gist.github.com/MustafaFerhan/25906d2be6ca109f61ce#file-evaluatejavascript-string-problem

回答by Alex Escobar

This worked for me

这对我有用

json = json.replace("\\"","'");
JSONObject jo = new JSONObject(json.substring(1,json.length()-1));

回答by Nic Raboy

I think the problem may be in the charset that you are trying to use. It is probably best to use UTF-8 instead of iso-8859-1.

我认为问题可能出在您尝试使用的字符集中。最好使用 UTF-8 而不是 iso-8859-1。

Also open whatever file is being used for your InputStream and make sure no special characters were accidentally inserted. Sometimes you have to specifically tell your editor to display hidden / special characters.

还要打开用于 InputStream 的任何文件,并确保没有意外插入特殊字符。有时您必须特别告诉您的编辑器显示隐藏/特殊字符。

回答by user4879711

return response;

After that get the response we need to parse this By:

之后得到响应,我们需要解析这个通过:

JSONObject myObj=new JSONObject(response);

On response there is no need for double quotes.

响应时不需要双引号。

回答by Jamal

I made this change and now it works for me.

我做了这个改变,现在它对我有用。

//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);

回答by Rasel

In my case the problem occured from phpfile. It gave unwanted characters.That is why a json parsingproblem occured.

在我的情况下,问题出在php文件中。它给出了不需要的字符。这就是出现json parsing问题的原因。

Then I paste my php codein Notepad++and select Encode in utf-8 without BOMfrom Encodingtab and running this code-

然后我粘贴我php codeNotepad++Encode in utf-8 without BOMEncoding选项卡中选择并运行此代码 -

My problem gone away.

我的问题消失了。