package cn.kjxy.JSON; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*json解析需要导入json-lib.jar包,安卓自带而非Java */
class Student{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
} }
public class Demo1 {
public static void main(String[] args) {
try {
//json数据描述学生对象
//格式一 {}-->JSONObject解析
String json = "{name:'张三',age:18}";
JSONObject jsonObject = new JSONObject(json);
Student student = new Student();
student.setName(jsonObject.getString("name"));
student.setAge(jsonObject.getInt("age"));
System.out.println(student);
///格式二 [] -->JSONArray解析
String array = "['张三','李四','王五']";
JSONArray jsonArray = new JSONArray(array);
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.getString(i)); } } catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}