类型java.lang.String的值不能转换为JSONArray

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

这是错误:

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

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

}]

用于获取字符串值的类:

 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;

}

}

这是转换为JSONArray:

String jsonObjRecv = JSONGet.getJSONfromURL(URL_LIST);

JSONArray jsonArr = new JSONArray(jsonObjRecv);

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

回答:

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

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

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

或从此链接https://repo1.maven.org/maven2/com/googlecode/json-simple/json-

simple/1.1.1/json-simple-下载链接库“ json-simple-1.1.1.jar”

1.1.1.jar

然后,您可以轻松解析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"

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

以上是 类型java.lang.String的值不能转换为JSONArray 的全部内容, 来源链接: utcz.com/qa/418048.html

回到顶部