1、JsonReader
public void parseJson(String json){
try{
//创建JsonReader;
JsonReader reader=new JsonReader(new StringReader(json));
reader.beginArray();
while(reader.hasNext()){
reader.beginObject();
while(reader.hasNext()){
String tagName=reader.nextName();
if(tagName.equals("name")){
Log.d("shuai","name:"+reader.nextString());
}else if(tagName.equals("age")){
Log.d("shuai","age:"+reader.nextString));
}
}
reader.endObject();
}
reader.endArray();
}catch(Exception e){
e.printStackTrace();
}
}
2、Gson
要加入Gson jar包
public void ParseJson(String json){
Gson gson=new Gson();
User user=gson.fromJson(json,User.class);
Log.d("shuai","name:"+user.getName());
Log.d("shuai","age:"+user.getAge());
}
Gson解析JSON数组
Type listType=new TypeToken<List<User>>(){}.getType();
Gson gson=new Gson();
List<User> users=gson.fromJson(jsonData,listType);
for(Iterator<User> iterator=users.iterator();iterator.hasNext();){
User user=(User)iterator.next();
Log.d("shuai","name:"+user.getName());
Log.d("shuai","age:"+user.getAge());
}
3、JsonArray解析Json数组
String jsonStr = new String(baos.toByteArray());
JSONArray json = new JSONArray(json);
// 解析一个JSON数组
List<User> vedioNews = new ArrayList<User>();
for (int i = 0; i < json.length(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
User user = new User(jsonObject.getInt("id"),jsonObject.getString("name"),jsonObject.getInt("age"));
User.add(user);
}