1 String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]"; 2 try{ 3 JsonReader reader = new JsonReader(new StringReader(jsonData)); 4 reader.beginArray(); 5 while(reader.hasNext()){ 6 reader.beginObject(); 7 while(reader.hasNext()){ 8 String tagName = reader.nextName(); 9 if(tagName.equals("username")){ 10 System.out.println(reader.nextString()); 11 } 12 else if(tagName.equals("userId")){ 13 System.out.println(reader.nextString()); 14 } 15 } 16 reader.endObject(); 17 } 18 reader.endArray(); 19 } 20 catch(Exception e){ 21 e.printStackTrace(); 22 }
通过把JSON数据映射成一个对象,使用Gson对象的fromJson()方法获取一个对象数组进行操作:
创建JSON数据对应的一个POJO对象User.java:
代码如下:
1 public class User { 2 private String username ; 3 private int userId ; 4 public String getUsername() { 5 return username; 6 } 7 public void setUsername(String username) { 8 this.username = username; 9 } 10 public int getUserId() { 11 return userId; 12 } 13 public void setUserId(int userId) { 14 this.userId = userId; 15 } 16 }
使用Gson对象获取User对象数据进行相应的操作:
代码如下:
1 String jsonData = "{\"username\":\"arthinking\",\"userId\":001}"; 2 Gson gson = new Gson(); 3 User user = gson.fromJson(jsonData, User.class); 4 System.out.println(user.getUsername()); 5 System.out.println(user.getUserId());
原文:http://www.cnblogs.com/jiuqing/p/4014685.html