代码很简单,大家看看就知道。
首先先上json文件,命名为newdata.json:此文件放在assets文件夹下:
[
{
"name": "zhangsan",
"age": 156,
"love":[
"app","lll"
]
},
{
"name": "lisi",
"age": 16,
"love":[
"gaoshu"
]
},
{
"name": "wangwu",
"age": 36
}
]
读取代码:
try {
InputStream is = null;
try {
is = getAssets().open("newdata.json");
JsonReader reader = new JsonReader(new InputStreamReader(is));
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
String doing = "";
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("name")) {
doing += reader.nextString();
}
else if (name.equals("age") || reader.peek() != JsonToken.NULL) { // 当前获取的字段是否为:null
doing += reader.nextString();
}
else if (name.equals("love")) {
reader.beginArray();
while(reader.hasNext()) {
doing+=reader.nextString();
}
reader.endArray();
}
}
Log.i(TAG, "doing: "+doing.toString());
reader.endObject();
}
reader.endArray();
}
finally {
// is.close();
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
注意一点的是:JsonReader是Android 3.0引入的新解析类,必须在API Level为honeycomb中的SDK以及固件在3.0上才能使用大家可以去官网看看:http://developer.Android.com/reference/android/util/JsonReader.html