我有这样的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"]
这是String
["04","19","34","47","59"]
我想获得String []标签,其中:
tab[0] = "04";
tab[1] = "19";
...
答案 0 :(得分:1)
我认为你的json返回的不是你想要的。你可能想要一个关键字数组:5
,6
,但是你的json显示的只是一个字符串,所以如果你能控制服务器返回的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;
}