gpt4 book ai didi

java - Android JSON 解析问题

转载 作者:行者123 更新时间:2023-12-01 10:51:38 25 4
gpt4 key购买 nike

我有这样的 Json:

{
"id": 226112,
"name": "name",
"min": 1,
"km": "0.33",
"url": "5___2_2.htm",
"departures": [
{
"type": "DATA",
"departures": {
"5": [
"04",
"19",
"34",
"47",
"59"
],
"6": [
"11",
"23",
"35",
"47",
"59"
]
etc..

我尝试解析它:

private static final String TAG_DEPARTURES = "departures";
private static final String TAG_TYPE = "type";
private static final String TAG_DEPARTURES2 = "departures";
private static String TAG_HOUR = "5";

...
example

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);

timetables = jsonObj.getJSONArray(TAG_DEPARTURES);

for (int i = 0; i < timetables.length(); i++) {
JSONObject c = timetables.getJSONObject(i);

String type = c.getString(TAG_TYPE);

JSONObject departures = c.getJSONObject(TAG_DEPARTURES2);
String hour = departures.getString(TAG_HOUR);

HashMap<String, String> timetable = new HashMap<String, String>();

timetable.put(TAG_TYPE, type);
timetable.put(TAG_DEPARTURES2, hour);

timetableList.add(timetable);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
...

我终于明白了:

DATA ["04","19","34","47","59"]

这是字符串

["04","19","34","47","59"]

我想要获取 String[] 选项卡,其中:

tab[0] = "04";
tab[1] = "19";
...

最佳答案

我认为你返回的 json 不是你想要的。也许你想要一个键数组:5,6,但是你的 json 显示的问题只是一个string,所以如果你可以控制服务器返回的json,请将其格式更改为字符串数组。

如果你无法控制返回的json,你应该自己提取真正的字符串,如下所示:

public String[] extractArray(final String str){
final String strNoBrace = str.substring(1,str.length()-1);
String[] tempResult = strNoBrace.split(",");
if(tempResult==null) return null;
String[] result = new String[tempResult.size()];
for(int i=0,size=tempResult.size();i<size;++i){
String temp = tempResult[i];
result[i] = temp.substring(1,temp.length()-1);
}
return result;
}

关于java - Android JSON 解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844560/

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