标签:
之前试过用geon还有fastjson但是老是报错。还是用原生自带的json方法。这里我来接受一组json数据
譬如我们想要获取一堆人员信息,
[ {"username":"马晕","company":"albaba"}, {"username":"刘强西","company":"jingdong"}, {"username":"马花疼","company":"qq"}, {"username":"李艳红","company":"baidu"} ]
这里我们根据我们获得的数据进行映射:生成一个人员类实体
public class User implements Serializable { private String username; private String company; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } }
那我们在做一个UserList的实体类 用来转换json数据为了对象组
public class UserList implements Serializable { private List<User> userList= new ArrayList<User>(); //信息组的人员的总人数 private int usersCount; public int getUsersCount() { return usersCount; } public List<User> getUserList() { return userList; } //解析json并转化成对象组 public static UserList parse(JSONArray obj) throws JSONException { UserList list = new UserList(); if(null != obj){ //获取对象组长度作为总人数 list.usersCount = obj.length(); for(int i=0;i<obj.length();i++){ JSONObject userJson = obj.getJSONObject(i); User user = new User(); user.setUsername(userJson.getString("username")); user.setCompany(userJson.getString("company")); list.userList.add(user); } } return list; } }
String usersString = "[ {"username":"马晕","company":"albaba"}, {"username":"刘强西","company":"jingdong"}, {"username":"马花疼","company":"qq"}, {"username":"李艳红","company":"baidu"} ]";
/** * 字符串转JSON * * @param json * @return * @throws JSONException */ public static JSONArray toJSONArray(String json) throws JSONException { return new JSONArray(json); }
用安卓自带的原生方法解析从webservice获取的json数据
标签:
原文地址:http://blog.csdn.net/huangxulei/article/details/43930273