1 package cn.kjxy.JSON; 2 3 import org.json.JSONArray; 4 import org.json.JSONException; 5 import org.json.JSONObject; 6 /** 7 *json解析需要导入json-lib.jar包,安卓自带而非Java 8 9 */ 10 class Student{ 11 private String name; 12 private int age; 13 public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public int getAge() { 20 return age; 21 } 22 public void setAge(int age) { 23 this.age = age; 24 } 25 @Override 26 public String toString() { 27 return "Student [name=" + name + ", age=" + age + "]"; 28 } 29 30 } 31 public class Demo1 { 32 public static void main(String[] args) { 33 try { 34 //json数据描述学生对象 35 //格式一 {}-->JSONObject解析 36 String json = "{name:'张三',age:18}"; 37 JSONObject jsonObject = new JSONObject(json); 38 Student student = new Student(); 39 student.setName(jsonObject.getString("name")); 40 student.setAge(jsonObject.getInt("age")); 41 System.out.println(student); 42 ///格式二 [] -->JSONArray解析 43 String array = "['张三','李四','王五']"; 44 JSONArray jsonArray = new JSONArray(array); 45 for (int i = 0; i < jsonArray.length(); i++) { 46 System.out.println(jsonArray.getString(i)); 47 48 } 49 50 } catch (JSONException e) { 51 // TODO Auto-generated catch block 52 e.printStackTrace(); 53 } 54 } 55 }