Use the native method provided by Android to parse json data obtained from webservice
After studying oschina, the information obtained is all in xml. It doesn't feel as good as json, And the parsing is too complicated. xml is too much to be compared with json, Which is troublesome.
I tried to use geon and fastjson before, but I always reported an error. Or use the native json method. Here I will accept a group of json data
For example, if we want to obtain a bunch of personnel information,
[{"Username": "Ma dizzy", "company": "albaba" },{ "username": "Liu qianxi", "company": "jingdong "}, {"username": "Mahua pain", "company": "qq" },{ "username": "Li Yanhong", "company": "baidu"}]
The above information is a group of people with two field names and the company
Here we map based on the data we get: generate a person-class entity
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;}}
How can we convert the above json group data into a one-member group? Here we can use List To obtain json data.
Then we are creating a UserList object class to convert json data into an object group.
Public class UserList implements Serializable {private List
UserList = new ArrayList
(); // Total number of persons in the Information Group: private int usersCount; public int getUsersCount () {return usersCount;} public List
GetUserList () {return userList;} // parse json and convert it to the object group public static UserList parse (JSONArray obj) throws JSONException {UserList list = new UserList (); if (null! = Obj) {// obtain the object group length as the total number list. usersCount = obj. length (); for (int I = 0; I
The above resolution parameter is a json object group, which can be very simple here,
String usersString = "[{" username ":" Ma dizzy "," company ":" albaba "},{" username ":" Liu qianxi "," company ": "jingdong" },{ "username": "Mahua pain", "company": "qq" },{ "username": "Li Yanhong", "company ": "baidu"}] ";
Assume that the json data we obtain is a string, which is generally a string. Then we use the built-in java method to convert it to JSONArray.
/*** Convert String to JSON ** @ param json * @ return * @ throws JSONException */public static JSONArray toJSONArray (String json) throws JSONException {return new JSONArray (json );}
We also wrote a method to convert string to JSONArray.
I don't want to write it here. Is it very easy? I hope to give you an opportunity.