try {
InputStream is = getAssets().open("city.txt");
String json = Utils.readIputStream(is);
//解析json数据
JSONObject result = new JSONObject(json);
JSONObject obj = result.getJSONObject("result");//result是city中的字段
for (int i = 0; i < letters.length; i++) {
/**
* 先判断这个字母有没有对应的数据
*/
if (obj.has(letters[i])) {
/**
* 有的话,就进行乡下解析,city中下面的是一个数组
*/
JSONArray array = obj.getJSONArray(letters[i]);
int len = array.length();
mList.add(letters[i]);
for(int j= 0;j<len;j++){
JSONObject o = array.getJSONObject(j);
City city = new City();
city.name = o.getString("name");
city.code = o.getString("code");
mList.add(city);
}
}
}
cityAdapter mAdapter = new cityAdapter();
mListView.setAdapter(mAdapter);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Utils 类中输入输出流代码
public class Utils {
public static String readIputStream(InputStream is) throws IOException {
String json = null;
byte [] buff = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
while((len = is.read(buff))!=-1){
baos.write(buff,0,len);
}
baos.flush();
baos.close();
is.close();
json = new String(baos.toByteArray(),"utf-8");
return json;
}