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

RCK*_*K69 59 parsing android json

我有一个带有2个JSON-Arrays的JSON文件:一个用于路由的数组和一个用于景点的数组.

路线应包含用户导航到的多个景点.不幸的是我收到错误:

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

这是我的变量和解析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;
}
Run Code Online (Sandbox Code Playgroud)

Log.i("JSON Parser",json); 告诉我,在生成的字符串的开头有一个奇怪的符号:在此输入图像描述

但错误发生在这里:

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

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

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

kha*_*ntt 39

原因是在撰写String时添加了一些不需要的字符.临时解决方案是

return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
Run Code Online (Sandbox Code Playgroud)

但是尝试删除源String上的隐藏字符.


Zaz*_*Gmy 37

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

的JSONObject

public JSONObject(java.lang.String source)
           throws JSONException
Run Code Online (Sandbox Code Playgroud)

从源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.
Run Code Online (Sandbox Code Playgroud)

你尝试使用一些东西:

new JSONObject("{your string}")
Run Code Online (Sandbox Code Playgroud)


MTu*_*ash 17

几天有同样的问题.最后找到了解决方案.PHP服务器返回了一些您在LOG或System.out中看不到的看不见的字符.

所以解决方案是我试图逐个子串起我的json String,当我来到substring(3)时,错误就消失了.

BTW.我在两边都使用了UTF-8编码.PHP方面:header('Content-type=application/json; charset=utf-8');

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

所以一个接一个地尝试1,2,3,4 ......!希望它可以帮助你们!

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

  • 我有同样的问题,但无法看到如何制作一个子串将使它消失? (4认同)

izb*_*ick 8

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

}
Run Code Online (Sandbox Code Playgroud)


小智 8

这对我有用

json = json.replace("\\\"","'");
JSONObject jo = new JSONObject(json.substring(1,json.length()-1));
Run Code Online (Sandbox Code Playgroud)


Mus*_*han 6

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

JsonParser parser = new JsonParser();
String retVal = parser.parse(param).getAsString();
Run Code Online (Sandbox Code Playgroud)

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


Nic*_*boy 5

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

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