String jsonData = "[{"username":"arthinking","userId":001},{"username":"Jason","userId":002}]"; try{ JsonReader reader = new JsonReader(new StringReader(jsonData)); reader.beginArray(); while(reader.hasNext()){ reader.beginObject(); while(reader.hasNext()){ String tagName = reader.nextName(); if(tagName.equals("username")){ System.out.println(reader.nextString()); } else if(tagName.equals("userId")){ System.out.println(reader.nextString()); } } reader.endObject(); } reader.endArray(); } catch(Exception e){ e.printStackTrace(); }
通过把JSON数据映射成一个对象,使用Gson对象的fromJson()方法获取一个对象数组进行操作:
创建JSON数据对应的一个POJO对象User.java:
public class User { private String username ; private int userId ; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } }
使用Gson对象获取User对象数据进行相应的操作:
Type listType = new TypeToken<LinkedList<User>>(){}.getType(); Gson gson = new Gson(); LinkedList<User> users = gson.fromJson(jsonData, listType); for (Iterator iterator = users.iterator(); iterator.hasNext();) { User user = (User) iterator.next(); System.out.println(user.getUsername()); System.out.println(user.getUserId()); }
如果要处理的JSON字符串只包含一个JSON对象,则可以直接使用fromJson获取一个User对象:
String jsonData = "{"username":"arthinking","userId":001}"; Gson gson = new Gson(); User user = gson.fromJson(jsonData, User.class); System.out.println(user.getUsername()); System.out.println(user.getUserId());