gpt4 book ai didi

java - JSONArray 无法转换为 JSONObject 异常

转载 作者:行者123 更新时间:2023-11-30 03:02:23 25 4
gpt4 key购买 nike

我有一个按以下方式构造的 JSON 字符串,它会抛出异常,将其传递给 JSONArray timeJSONArray = new JSONArray(time);

这是错误 Value [{"daysByte":158,"from":1020,"to":1260},{"daysByte":96,"from":1020,"to":1320 }] at 0 of type org.json.JSONArray无法转换为JSONObject这就是我接收数组的方式,但我无法更改它,所以我在将其转换为JSON对象而不是JSON 字符串,这是它当前的格式。我做错了什么?

[   
[
{
"daysByte":30,
"from":660,
"to":1290
},
{
"daysByte":96,
"from":660,
"to":1320
},
{
"daysByte":128,
"from":1050,
"to":1290
}
],
[
{
"daysByte":252,
"from":690,
"to":840
},
{
"daysByte":252,
"from":1050,
"to":1260
}
]
]

这是我正在使用的代码。我正在获取以字符串形式传入的值

public ArrayList<String> getTimeList(String time){

System.out.println("PLACES ACTIVITY " + time);
ArrayList<String> times = new ArrayList<>();
try{
//JSONObject timeJSONObject = new JSONObject(time);
JSONArray timeJSONArray = new JSONArray(time);
ArrayList<LegacyTimeSpan> timeSpanList = new ArrayList<>();

LegacyTimeSpanConverterImpl converter = new LegacyTimeSpanConverterImpl();


for(int i = 0; i < timeJSONArray.length(); i++){

int daysByte = timeJSONArray.getJSONObject(i).getInt("daysByte");
int from = timeJSONArray.getJSONObject(i).getInt("from");
int to = timeJSONArray.getJSONObject(i).getInt("to");

System.out.println("TO " + to);

LegacyTimeSpan timeSpan = new LegacyTimeSpan(daysByte, from, to);
timeSpanList.add(timeSpan);

}

Log.d("Time span list", timeSpanList.toString());
WeekSpan weekSpan = converter.convertToWeekSpan(timeSpanList);
List<DayTimeSpanPair> dayTimeSpanPair = weekSpan.toDayTimeSpanPairs();
for(int i = 0; i< dayTimeSpanPair.size(); i++){

String timeRange = buildTimeString(dayTimeSpanPair.get(i));
times.add(timeRange);


}
} catch(JSONException e){
Log.d("PLACES EXCEPTION JSON",e.getMessage());
}

return times;
}

最佳答案

This Code should work i think as u declare the json Format.

             [
[
{
} ,{},{} // Json Object Structure as u defined in you Question
topArray = ],
[
{
},{},{}
]
]


for(JSONArray objArray : topArray){
for(JSONObject eachObject : objArray){
System.out.println(eachObject.get("daysByte"););
System.out.println(eachObject.get("from");
System.out.println(eachObject.get("to");
}
}

关于java - JSONArray 无法转换为 JSONObject 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35644981/

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