Java实现JSONObject对象与Json字符串互相转换 JSONObject 转 JSON 字符串 Java代码: JSONObject jsonObject = new JSONObject (); jsonObject . put ( "name" , "wjw" ); jsonObject . put ( "age" , 22 ); jsonObject . put ( "sex" , "男
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"));
执行结果:
wjw22
实体类 转 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
【版权声明】本博文著作权归作者所有,任何形式的转载都请联系作者获取授权并注明出处!
【重要说明】本文为本人的学习记录,论点和观点仅代表个人而不代表当时技术的真理,目的是自我学习和有幸成为可以向他人分享的经验,因此有错误会虚心接受改正,但不代表此刻博文无误!
【Gitee地址】秦浩铖:https://gitee.com/wjw1014