gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:07:27 28 4
gpt4 key购买 nike

我花了 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 响应。

您需要将json-simple 库添加到您的项目中,方法是将其添加到gradle:

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

或从此链接下载库“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

然后你就可以很容易地解析你的 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 - 类型 java.lang.String 的值无法转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18174064/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com