Value of type java.lang.String cannot be converted to JSONArray

后端 未结 4 1105
情深已故
情深已故 2020-12-02 02:55

I\'ve spent 2 days to find a solution with of problem.

Here is the error:

E/log_tag: Error parsing data org.json.JSONException: Value of type java.l         


        
4条回答
  •  我在风中等你
    2020-12-02 03:34

    JSON data should always be encoded in UTF-8 (and your data most likely is). However, you read it using the ISO-8859-1. Since your JSON data contains Cyrillic characters, they will lead to invalid data that can no longer be parsed as JSON. (In UTF-8, Cyrillic characters required two bytes. However, ISO-8859-1 treats each byte as a separate character.)

    The fix is to use the correct encoding, most likely UTF-8:

    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
    

    Update:

    The code you're using is posted all over the Internet, sometimes with ISO-8859-1 and sometimes with UTF-8. If you stick to the standards, JSON with ISO-8859-1 encoding is invalid.

    The Android JSON parser is very unfortunate because it only supports strings as a parsing source. As a result, the complex code you're using is required to parse a JSON HTTP response. Memory and processing wise, it's pretty inefficient. It would be nice if Google would extend the JSON parser to directly work on an InputStream instance without taking the detour via a huge String instance.

    Update 2:

    I just realized that Android (starting with API level 11) contains a JSON parser working on InputStream. However, it's in a different package and only produces a stream of tokens, not JSONObject or JSONArray instances. I guess I'll write the missing code myself to come up with an easy to use and efficient JSON parser (producing JSONObject or JSONArray instances).

    Update 3:

    If the JSON text to parse is invalid, Android throw an exception containing the message:

    Value [{ "Id": "5207fc6473516724343ce7a5", "Name": "Эриван", ... }] of type java.lang.String cannot be converted to JSONArray
    

    Since there is not JSON data between the word Value and of in your message, I suspect that your JSON data is in fact empty.

    In your code, you should first check the status code of the HTTP response (getStatusLine().getStatusCode()). Furthmore, I seems strange that you use a POST request without posting any data. Shouldn't you use a GET request?

提交回复
热议问题