1.JSONObject从String中得到数据,提取数据,并且输出数据
String jsonStr = "{\"password\":\"123456\",\"username\":\"张三\"}";
JSONObject jsonObj = JSONObject.fromObject(jsonStr);//从字符串转成java代码
System.out.println("jsonObj-->"+jsonObj);//jsonObj-->{"password":"123456","username":"张三"}
String username = jsonObj.getString("username");//两种方法得到java代码
String password = jsonObj.optString("password");
System.out.println("json--->java\n username=" + username + "\t password=" + password);
//json--->java
username=张三 password=123456
2.JSONObject从hashmap中得到数据
Map map=new HashMap();
map.put("我","妹");
map.put("擦","哇");
map.put("你","呀");
JSONObject json = JSONObject.fromObject(map);
System.out.println("json-->"+json);//json-->{"我":"妹","擦":"哇","你":"呀"}
3.JSONObject直接添加数据
JSONObject jsonObj2 = new JSONObject();
jsonObj2.put("username", "张三");
jsonObj2.put("password", "123456");
jsonObj2.put("username2", "张三");
jsonObj2.put("password2", "123456");
System.out.println("java--->json \n" + jsonObj2.toString());
//java--->json
{"username":"张三","password":"123456","username2":"张三","password2":"123456"}
4.JSONObject从字符串转话成对象数据
String json3 = "{id:'1001',name:'张三',age:'22'}";
Student stu = new Student();
JSONObject obj = JSONObject.fromObject(json3);
stu = (Student)JSONObject.toBean(obj, Student.class);
System.out.println(stu);//1001, 张三, 22
public class Student {
private int id ;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public String toString(){
return this.id + ", " + this.name + ", " + this.age;
}
}