java.lang.String 类型的值无法转换为 JSONArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18174064/
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-11 23:02:10  来源:igfitidea点击:

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

javaandroidjson

提问by Anton Kashpor

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

我花了 2 天的时间来找到问题的解决方案。

Here is the error:

这是错误:

E/log_tag: Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray

Here is JSON:

这是JSON:

[
{
    "Id": "5207fc6473516724343ce7a5",
    "Name": "Эриван",
    "Types": [
        "Ресторан"
    ],
    "Latitude": 53.904752,
    "Longitude": 27.521095,
    "OperatingTime": [
        {
            "Day": 1,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 2,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 3,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 4,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 5,
            "Start": "10:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 6,
            "Start": "08:00:00",
            "Finish": "23:00:00"
        },
        {
            "Day": 0,
            "Start": "08:00:00",
            "Finish": "23:00:00"
        }
    ],
    "IsBookingAvailable": false
}]

Class for getting String value:

获取字符串值的类:

 public class JSONGet {

    public static String getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // Download JSON data from URL
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

        // Convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }

        try{

            jArray = new JSONArray(result);
        }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return result;
    }
  }

And here is converting to JSONArray:

这里正在转换为 JSONArray:

String jsonObjRecv = JSONGet.getJSONfromURL(URL_LIST);

JSONArray jsonArr = new JSONArray(jsonObjRecv);

I was trying to get Json object then convert it into Json array but I received the same error.

我试图获取 Json 对象,然后将其转换为 Json 数组,但我收到了相同的错误。

采纳答案by arshu

The problem is that your JSON is in the incorrect format. I have tried with your sample JSON and found the solution to it. Now the inbuilt JSONObject and JSONArray cannot be used to get such a json response.

问题是您的 JSON 格式不正确。我已尝试使用您的示例 JSON 并找到了解决方案。现在无法使用内置的 JSONObject 和 JSONArray 来获取此类 json 响应。

You need to add json-simple library to your project by adding it to gradle:

您需要通过将 json-simple 库添加到 gradle 来将其添加到您的项目中:

implementation 'com.googlecode.json-simple:json-simple:1.1.1'

Or download the library "json-simple-1.1.1.jar" from this link https://repo1.maven.org/maven2/com/googlecode/json-simple/json-simple/1.1.1/json-simple-1.1.1.jar

或从此链接下载库“json-simple-1.1.1.jar” https://repo1.maven.org/maven2/com/googlecode/json-simple/json-simple/1.1.1/json-simple- 1.1.1.jar

Then you can parse your JSON easily and it won't give any error. I have made a small sample code for you on how to use it :

然后你可以轻松解析你的 JSON,它不会给出任何错误。我为您制作了一个关于如何使用它的小示例代码:

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;

JSONParser parser_obj = new JSONParser();
JSONArray array_obj = (JSONArray) parser_obj.parse("String from web service"); 
// in your case it will be "result" 

Then you can process it as per your need.

然后,您可以根据需要对其进行处理。

回答by waqaslam

Your Json response seems just fine. However its not always guaranteed that the response string is always filled up with data. For that, I would suggest you to handle your array as below:

您的 Json 响应似乎很好。然而,它并不总是保证响应字符串总是充满数据。为此,我建议您按如下方式处理您的数组:

JSONArray jsonArr = null;

String jsonObjRecv = JSONGet.getJSONfromURL(URL_LIST);
if(!TextUtils.isEmpty(jsonObjRecv)){
    jsonArr = new JSONArray(jsonObjRecv);
}
else{
    Log.w("json", "jsonObjRecv is null");
}

回答by Codo

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.)

JSON 数据应始终以 UTF-8 编码(您的数据很可能是)。但是,您使用 ISO-8859-1 阅读它。由于您的 JSON 数据包含西里尔字符,它们将导致无法再解析为 JSON 的无效数据。(在 UTF-8 中,西里尔字符需要两个字节。但是,ISO-8859-1 将每个字节视为一个单独的字符。)

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

解决方法是使用正确的编码,很可能是 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.

您使用的代码发布在整个 Internet 上,有时使用 ISO-8859-1,有时使用 UTF-8。如果您坚持标准,带有 ISO-8859-1 编码的 JSON 是无效的。

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 InputStreaminstance without taking the detour via a huge Stringinstance.

Android JSON 解析器非常不幸,因为它只支持字符串作为解析源。因此,解析 JSON HTTP 响应需要您使用的复杂代码。内存和处理明智,它是非常低效的。如果 Google 将 JSON 解析器扩展为直接在InputStream实例上工作,而无需通过巨大的String实例绕道而行,那就太好了。

Update 2:

更新 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 onlyproduces a stream of tokens, not JSONObjector JSONArrayinstances. I guess I'll write the missing code myself to come up with an easy to use and efficient JSON parser (producing JSONObjector JSONArrayinstances).

我刚刚意识到 Android(从 API 级别 11 开始)包含一个处理InputStream. 但是,它位于不同的包中,生成令牌流,而不是JSONObjectJSONArray实例。我想我会自己编写缺少的代码来提出一个易于使用且高效的 JSON 解析器(生成JSONObjectJSONArray实例)。

Update 3:

更新 3:

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

如果要解析的 JSON 文本无效,Android 会抛出包含以下消息的异常:

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

Since there is not JSON data between the word Valueand ofin your message, I suspect that your JSON data is in fact empty.

由于您的消息中单词Valueof之间没有 JSON 数据,我怀疑您的 JSON 数据实际上是空的。

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?

在您的代码中,您应该首先检查 HTTP 响应的状态代码 ( getStatusLine().getStatusCode())。此外,您使用 POST 请求而不发布任何数据似乎很奇怪。你不应该使用 GET 请求吗?

回答by Adil Malik

In my case I was not decoding the jSon string before parsing it as jSon object. The following worked for me.

就我而言,在将 jSon 字符串解析为 jSon 对象之前,我没有对其进行解码。以下对我有用。

JSONObject responseJSonObj = new JSONObject( URLDecoder.decode( result, "UTF-8" ) );

Where resultcontains the jSon string to be parsed.

whereresult包含要解析的 json 字符串。