net.sf.json.JSONObject实现Object对象与Json字符串的互转        前⾯看了,下⾯来看下net.sf.json.JSONObject实现Object对象与Json字符串的互转。
JSONUtil.java
package com.bijian.study;
import net.sf.json.JSONObject;
public class JSONUtil {
public static void main(String[] args) {
testJsonBean();
}
/**
* java对象与json对象互相转换
*/
private static void testJsonBean() {
/**
* 创建java对象
*/
Student student = new Student();
student.setId(1);
student.setName("李四");
student.setSex("man");
student.setAge(25);
student.setHobby(new String[] { "篮球", "上⽹", "跑步", "游戏" });
/**
* java对象转换成json对象,并获取json对象属性
*/
JSONObject jsonStu = JSONObject.fromObject(student);
System.out.String());
System.out.JSONArray("hobby"));
/**
* json对象转换成java对象,并获取java对象属性
*/
Student stu = (Student) Bean(jsonStu, Student.class);
System.out.println(stu);
/**
* 创建json对象
object to*/
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 1);
jsonObj.put("name", "张勇");
jsonObj.put("sex", "男");
jsonObj.put("age", 24);
jsonObj.put("hobby",new String[]{"上⽹","游戏","跑步","⾳乐"});
System.out.String());
/**
* json对象转换成java对象
*/
Student stud = (Student) Bean(jsonObj, Student.class);
System.out.println(stud);
}
}
Student.java
package com.bijian.study;
import java.util.Arrays;
public class Student {
private int id;
private String name;
private String sex;
private int age;
private String[] hobby;
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + ", hobby="
+ String(hobby) + "]";
}
}
如运⾏时报java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher异常,请参考:。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。