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]

*/

}
}


GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 4 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐