日期:2014-05-16 浏览次数:20432 次
static ArrayList<Contact> parseJson(String JsonData){ ArrayList<Contact>list = null; JsonReader reader = new JsonReader(new StringReader(JsonData)); try { // 开始解析JSON数组 reader.beginArray(); // 循环读取JSON中的数组 list=new ArrayList<Contact>(); while(reader.hasNext()){ // 开始解析JSON数组里的对象 reader.beginObject(); // 循环读取JSON数组中的对象 Contact con=new Contact(); while(reader.hasNext()){ String tagName = reader.nextName(); if(tagName.equals("username")); con.setUsername(reader.nextString()); if(tagName.equals("num")); con.setPhoneNum(reader.nextString()); /*else if(tagName.equals("num")) con.setPhoneNum(reader.nextString());*/ if(tagName.equals("name")){ con.setContact(reader.nextString()); } } list.add(con); reader.endObject(); } reader.endArray(); } catch (IOException e) { e.printStackTrace(); } return list; } }
List <Contact>ls=parseJson(s); for(Contact con:ls){ System.out.println(con.getUsername()); System.out.println(con.getContact()); System.out.println(con.getPhoneNum()); }
java.lang.IllegalStateException: Expected END_OBJECT but was NAME com.google.gson.stream.JsonReader.expect(JsonReader.java:323) com.google.gson.stream.JsonReader.endObject(JsonReader.java:314) JsonDemo.parsrJSON(JsonDemo.java:152) JsonDemo.doGet(JsonDemo.java:64) javax.servlet.http.HttpServlet.service(HttpServlet.java:617) javax.servlet.http.HttpServlet.service(HttpServlet.java:717)