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

前端 未结 14 2024
别那么骄傲
别那么骄傲 2020-11-22 07:10

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

A route should consist of several sights where the user gets navigated to

相关标签:
14条回答
  • 2020-11-22 07:37

    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.

    0 讨论(0)
  • 2020-11-22 07:40

    This is simple way (thanks Gson)

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

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

    0 讨论(0)
  • 2020-11-22 07:42

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

    JSONObject

    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.

    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}")
    
    0 讨论(0)
  • 2020-11-22 07:42

    For me, I just needed to use getString() vs. getJSONObject() (the latter threw that error):

    JSONObject jsonObject = new JSONObject(jsonString);
    String valueIWanted = jsonObject.getString("access_token"))
    
    0 讨论(0)
  • 2020-11-22 07:45

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

    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;
    
    }
    
    0 讨论(0)
  • 2020-11-22 07:46

    The 3 characters at the beginning of your json string correspond to Byte Order Mask (BOM), which is a sequence of Bytes to identify the file as UTF8 file.

    Be sure that the file which sends the json is encoded with utf8 (no bom) encoding.

    (I had the same issue, with TextWrangler editor. Use save as - utf8 (no bom) to force the right encoding.)

    Hope it helps.

    0 讨论(0)
提交回复
热议问题