在开发中经常会遇到解析json的问题
在这里总结几种解析的方式:
方式一:
json数据:
private String jsonData = "[{\"name\":\"Michael\",\"age\":20},{\"name\":\"Mike\",\"age\":21}]";解析jsonData的方法
try { //如果需要解析Json数据,首先要生成一个JsonReader对象 JsonReader reader=new JsonReader(new StringReader(jsonData)); reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); while (reader.hasNext()) { String tagName=reader.nextName(); if (tagName.equals("name")) { System.out.println("name--->"+reader.nextString()); }else if (tagName.equals("age")) { System.out.println("age--->"+reader.nextInt()); } } reader.endObject(); } reader.endArray(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private String jsonData="{\"name\":\"Michael\",\"age\":20}";
Gson gson=new Gson(); User user=gson.fromJson(jsonData, User.class); System.out.println("name-->"+user.getName()); System.out.println("age-->"+user.getAge());
public class User { private String name; private int age; 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 String jsonData = "[{\"name\":\"Michael\",\"age\":20},{\"name\":\"Mike\",\"age\":21}]";
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("name--->"+user.getName()); System.out.println("age--->"+user.getAge()); }
Android中解析Json数据,布布扣,bubuko.com
原文:http://blog.csdn.net/zhong1113/article/details/29672235