Java 解析JSON数据
1.先下载 gson.jar.http://code.google.com/p/google-gson/downloads/list
2.解压后,把gson-2.2.2.jar 复制到 java项目的libs文件夹内
Json数据:[{"name":"A","age":12},{"name":"B","age":14}]
JsonReader reader = new JsonReader(new StringReader(jsonData)); try { reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); while (reader.hasNext()) { String tagNameString = reader.nextName(); if(tagNameString.equals("name")){ System.out.print("name--->"+reader.nextString()); } else if(tagNameString.equals("age")){ System.out.print("age--->"+reader.nextInt()); } } reader.endObject(); } reader.endArray(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
方式二:通过类对象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } private int age; }
Type listType = new TypeToken<LinkedList<User>>(){}.getType(); Gson gson = new Gson(); LinkedList<User> users = gson.fromJson(jsonData,listType); for(int i =0;i<users.size();i++){ User user = users.get(i); System.out.println("name--->"+user.getName()); }