Java实现JSONObject对象与Json字符串互相转换
JSONObject 转 JSON 字符串
Java代码:
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "wjw");
jsonObject.put("age", 22);
jsonObject.put("sex", "男");
jsonObject.put("school", "商职");
String jsonStr = JSONObject.toJSONString(jsonObject);
System.out.println(jsonStr);
执行结果:
{"school":"商职","sex":"男","name":"wjw","age":22}
JSON 字符串 转 JSONObject 对象
Java代码:
String jsonStr = "{\"school\":\"商职\",\"sex\":\"男\",\"name\":\"wjw\",\"age\":22}";
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getInteger("age"));
执行结果:
wjw
22
实体类 转 JSONObject对象
创建Person类:
package c;
public class Person {
private String name; // 姓名
private int age; // 年龄
private String sex; // 性别
private String school; // 学校
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
创建 Person 对象:
Person person = new Person();
person.setName("wjw");
person.setAge(22);
person.setSex("男");
person.setSchool("商职");
String personStr = JSONObject.toJSONString(person); // 转换为json字符串
System.out.println("personStr:"+personStr);
JSONObject personObject = JSONObject.parseObject(personStr); // 转换为json对象
System.out.println("personObject:"+personObject);
System.out.println("name:"+personObject.getString("name"));
打印结果:
personStr:{"age":22,"name":"wjw","school":"商职","sex":"男"}
personObject:{"school":"商职","sex":"男","name":"wjw","age":22}
name:wjw