今天学习了简单的Json字符串解析示例:
Person.java:
public class Person { private String id; private String name; private String age; public void setId(String id){ this.id = id; } public String getId(){ return this.id; } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void setAge(String age){ this.age = age; } public String getAge(){ return this.age; } @Override public String toString() { return this.name + "~年方:" + this.age; } }
写一个解析上述Json字符串的方法:
private void parseEasyJson(String json){ persons = new ArrayList<Person>(); try{ JSONArray jsonArray = new JSONArray(json); for(int i = 0;i < jsonArray.length();i++){ JSONObject jsonObject = (JSONObject) jsonArray.get(i); Person person = new Person(); person.setId(i+""); person.setName(jsonObject.getString("name")); person.setAge(jsonObject.getString("age")); persons.add(person); } }catch (Exception e){e.printStackTrace();} }