try {
InputStream stream = getAssets().open("array.json");
String jsonStr=StreamToString.streamToStr(stream,"utf-8");
InputStream stream = getAssets().open("array.json");
String jsonStr=StreamToString.streamToStr(stream,"utf-8");
//使用gson解析
//method1(jsonStr);
//使用原生解析
//method2(jsonStr);
//method2(jsonStr);
//使用混合解析
method3(jsonStr);
} catch (Exception e) {
e.printStackTrace();
}
}
private void method3(String jsonStr) throws JSONException {
//集合对象
List<Result> resultList=new ArrayList<>();
//集合对象
List<Result> resultList=new ArrayList<>();
//json串最外层是[] ,首先要构造的对象 是 JSONArray
JSONArray array=new JSONArray(jsonStr);
for(int i=0;i<array.length();i++){
JSONArray array=new JSONArray(jsonStr);
for(int i=0;i<array.length();i++){
JSONObject obj = array.optJSONObject(i);
//使用gson解析
Gson gson=new Gson();
Result r=gson.fromJson(obj.toString(),Result.class);
resultList.add(r);
Gson gson=new Gson();
Result r=gson.fromJson(obj.toString(),Result.class);
resultList.add(r);
}
for(int i=0;i<resultList.size();i++){
Log.d("zzz",resultList.get(i).toString());
}
}
for(int i=0;i<resultList.size();i++){
Log.d("zzz",resultList.get(i).toString());
}
}
private void method2(String jsonStr) throws JSONException {
//集合对象
List<Result> resultList=new ArrayList<>();
//集合对象
List<Result> resultList=new ArrayList<>();
//json串最外层是[] ,首先要构造的对象 是 JSONArray
JSONArray array=new JSONArray(jsonStr);
for(int i=0;i<array.length();i++){
JSONObject obj = array.optJSONObject(i);
String name=obj.optString("name");
JSONArray array=new JSONArray(jsonStr);
for(int i=0;i<array.length();i++){
JSONObject obj = array.optJSONObject(i);
String name=obj.optString("name");
Result result=new Result();
result.setName(name);
resultList.add(result);
}
for(int i=0;i<resultList.size();i++){
Log.d("zzz",resultList.get(i).toString());
}
}
result.setName(name);
resultList.add(result);
}
for(int i=0;i<resultList.size();i++){
Log.d("zzz",resultList.get(i).toString());
}
}
private void method1(String jsonStr) {
//集合对象
List<Result> resultList=new ArrayList<>();
//集合对象
List<Result> resultList=new ArrayList<>();
//得到type类型
Type type=new TypeToken<List<Result>>(){}.getType();
Type type=new TypeToken<List<Result>>(){}.getType();
Gson gson=new Gson();
resultList=gson.fromJson(jsonStr,type);
resultList=gson.fromJson(jsonStr,type);
for(int i=0;i<resultList.size();i++){
Log.d("zzz",resultList.get(i).toString());
}
}
Log.d("zzz",resultList.get(i).toString());
}
}