Java对象转换为Json字符串及Json字符串转换为Java对象
1. 首先是Java对象转Json字符串.需要jar包.五个.分别如下:
commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
先定义一个普通JavaBean对象:
package com.jin.entity;
import java.io.Serializable;
public class Customer implements Serializable {
/**
*
*/
private static final long serialVersionUID = -872792784814226188L;
private String name;
private Integer age;
public Customer() {
super();
}
public Customer(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Customer [name=" + name + ", age=" + age + "]";
}
}
测试类:
package com.jin.json;
import com.jin.entity.Customer;
import net.sf.json.JSONObject;
public class JsonTest1 {
public static void main(String[] args) {
Customer custoemr = new Customer("张三",23); //创建一个人对象
JSONObject fromObject = JSONObject.fromObject(custoemr);
String string = fromObject.toString();
System.out.println(string);
//打印结果为: {"age":23,"name":"张三"}
}
}
2. Json字符串转换为Java对象.
package com.jin.json;
import com.jin.entity.Customer;
import net.sf.json.JSONObject;
public class JsonTest1 {
public static void main(String[] args) {
String json = "{name:'呵呵',age:24}"; //定义一个json格式的字符串.
JSONObject jsonObject = JSONObject.fromObject(json);
Customer c = (Customer) JSONObject.toBean(jsonObject, Customer.class);
System.out.println(c);
/*
* 打印结果为:Customer [name=呵呵, age=24]
*
*/
}
}
更多推荐
所有评论(0)