【Android】JSON应用

来源:互联网 发布:南京田家炳中学知乎 编辑:程序博客网 时间:2024/06/06 23:28

public ArrayList<Folk> jsonToObject(JSONArray jsonArray) {ArrayList<Folk> folks = new ArrayList<Folk>();try {for (int i = 0; i < jsonArray.length(); i++) {JSONObject json = jsonArray.getJSONObject(i);Folk folk = new Folk();folk.setName(json.optString("name"));folk.setAge(json.optString("age"));folk.setCareer(json.optString("career"));folk.setSalary(json.optInt("salary"));folk.setSex(json.optString("sex").equals("male") ? true: false);if (json.optString("list") != null&& json.optString("list").length() > 0) {folk.setList(jsonToObject(new JSONArray(json.optString("list"))));}folks.add(folk);}} catch (JSONException e) {e.printStackTrace();}return folks;}public String objectToJson() {List<Folk> fsk = new ArrayList<Folk>();Folk f2 = new Folk();f2.setAge("30岁");f2.setName("比尔");f2.setSex(false);fsk.add(f2);List<Folk> fs = new ArrayList<Folk>();Folk f1 = new Folk();f1.setAge("20岁");f1.setName("赵六");f1.setSex(true);f1.setList(fsk);fs.add(f1);String jsonData = null;List<Folk> folks = new ArrayList<Folk>();Folk f = new Folk();f.setAge("10岁");f.setName("张三");f.setSex(true);f.setList(fs);folks.add(f);f = new Folk();f.setAge("11岁");f.setName("李四");f.setSex(false);folks.add(f);f = new Folk();f.setAge("12岁");f.setName("王五");f.setSex(false);folks.add(f);try {return new JSONStringer().object().key("object").value(objectToJson(folks)).endObject().toString();} catch (JSONException e) {return null;}}private JSONArray objectToJson(List<Folk> folks) {JSONArray array = new JSONArray();try {StringBuilder builder = new StringBuilder();ArrayList<String> folksData = new ArrayList<String>();for (int i = 0; i < folks.size(); i++) {Folk folk = folks.get(i);JSONObject jsonObject = new JSONObject();jsonObject.put("name", folk.getName());jsonObject.put("sex", folk.isSex() ? "male" : "female");jsonObject.put("age", folk.getAge());jsonObject.put("career", folk.getCareer());jsonObject.put("salary", folk.getSalary());if (folk.getList() != null && folk.getList().size() > 0) {jsonObject.put("list", objectToJson(folk.getList()));}folksData.add(jsonObject.toString());array.put(jsonObject);}} catch (JSONException e) {e.printStackTrace();}return array;}public class Folk {String name;String career;String age;int salary;boolean sex;List<Folk> list;public List<Folk> getList() {return list;}public void setList(List<Folk> list) {this.list = list;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCareer() {return career;}public void setCareer(String career) {this.career = career;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}public int getSalary() {return salary;}public void setSalary(int salary) {this.salary = salary;}public boolean isSex() {return sex;}public void setSex(boolean sex) {this.sex = sex;}}


工程资源:http://download.csdn.net/detail/etzmico/3732722

原创粉丝点击