package com.testjson;
public class Person
{
private String name;
private Integer 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;
}
}
package com.testjson;
import net.sf.json.JSONObject;
public class test
{
public static void main(String[] args)
{
Person p = new Person();
p.setAge(11);
p.setName("测试");
JSONObject jsonObj1 = JSONObject.fromObject(p);
System.out.println("JSON输出后的:" + jsonObj1.toString());
JSONObject jsonObj2 = JSONObject.fromObject(jsonObj1);
System.out.println("JSONObject输出后的:" + jsonObj2.toString());
Person p2 = (Person)JSONObject.toBean(jsonObj1, Person.class);
System.out.println("json转化为对象:姓名:" + p2.getName() + ";年龄:" + p2.getAge());
/*********处理js格式问题************/
// JsonConfig config = new JsonConfig();
// config.setIgnoreDefaultExcludes(false);
// config.registerJsonBeanProcessor(Date.class, new JsDateJsonBeanProcessor());
/**************处理Integer为null时输出为0的问题 版本需要2.3**************/
// JsonConfig jsonConfig = new JsonConfig();
// jsonConfig.registerDefaultValueProcessor(Integer.class, new MyDefaultIntegerValueProcessor());
// JsonConfig jsonConfig = new JsonConfig();
// jsonConfig.findJsonValueProcessor(Integer.class, new DefaultValueProcessor()
// {
// public Object getDefaultValue(Class type)
// {
// return null;
// }
// });
}
}
package com.testjson;
import net.sf.json.JSONNull;
import net.sf.json.processors.DefaultValueProcessor;
public class MyDefaultIntegerValueProcessor implements DefaultValueProcessor
{
public Object getDefaultValue(Class type)
{
if (type != null && Integer.class.isAssignableFrom(type))
{
return Integer.valueOf(9999);
}
return JSONNull.getInstance();
}
}