package demo4;

import java.io.Serializable;

import net.sf.json.JSONString;

public class User implements JSONString,Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private long id;
private String name;
private String password;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(long id, String name, String password) {
super();
this.id = id;
this.name = name;
this.password = password;
} public User() {
super();
} public String toJSONString() {
return "{\"id\":"+this.id+",\"name\":\""+this.name+"\"}";
} }

user.java

package demo4;

public class Teacher {
private int id;
private String name;
private String password;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Teacher(int id, String name, String password) {
super();
this.id = id;
this.name = name;
this.password = password;
}
public Teacher() {
super();
} }

Teacher.java

package demo4;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonBeanProcessor;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter; import org.junit.Test; public class Demo {
/* public void registerJsonBeanProcessor(Class target,
JsonBeanProcessor jsonBeanProcessor) Registers a JsonBeanProcessor.
[Java -> JSON] Parameters:
target - the class to use as key
jsonBeanProcessor - the processor to register public void registerPropertyExclusion(Class target, *注册不转换的属性在类中 *
String propertyName) Registers a exclusion for a target class.
[Java -> JSON] Parameters:
target - the class to use as key
propertyName - the property to be excluded public void setExcludes(String[] excludes) 设置不转换的属性
Sets the excludes to use.
Will set default value ([]) if null.
[Java -> JSON] PropertyFilter: 属性过滤器
一个方法:
apply boolean apply(Object source,
String name,
Object value) Parameters:
source - the owner of the property
name - the name of the property
value - the value of the property
Returns:
true if the property will be filtered out, false otherwise */ /**
* 忽略不必要属性重写该对象指定toJSONString方法测试
*/
@Test
public void fun(){
User user=new User(12,"郭大侠","gz1234");
JSONObject jo=JSONObject.fromObject(user);
System.out.println(jo);
} /**
* 忽略不必要的属性,使用jsonConfig实现
* 通过jsonconfig实例,对包含和需要排除的属性进行方便的添加或删除
*/
@Test
public void fun1(){
Teacher t=new Teacher(12,"guodaxia","gz1234");
JsonConfig config=new JsonConfig();
config.setExcludes(new String[]{"password"});//设置排除password属性
JSONObject jo=JSONObject.fromObject(t, config);
System.out.println(jo);
} /**
* 测试使用属性过滤器达到前面的效果
* 使用propertyFilter可以允许同时对需要排除的属性和类进行控制,这种控制还可以是双向的,也可以应用到json字符串到java对象
*/
@Test
public void fun2(){
Teacher t=new Teacher(12,"guodaxia","gz1234");
JsonConfig config=new JsonConfig();
config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String propertyName, Object value) {
/**
* 就这样将Teacher类中的password属性过滤掉了
*/
// return source instanceof Teacher && "password".equalsIgnoreCase(propertyName);
return "password".equalsIgnoreCase(propertyName);//这个是测试它可以双向过滤
} });
JSONObject jo=JSONObject.fromObject(t, config);
System.out.println(jo);
JSONObject jo1=(JSONObject) JSONSerializer.toJSON("{'id':12,'name':'gz','password':'a12345'}", config);//这里使用JSONSerializer得到的JSON对象才有效可转换为Teacher对象,JSONObject.fromObject不行,不知为何
Teacher tt=(Teacher) jo1.toBean(jo1, Teacher.class );
System.out.println(tt.getId()+"--"+tt.getName()+"--"+tt.getPassword()); // JSONObject jo1=JSONObject.fromObject("{'id':12,'name':'gz','password':'a12345'}",config);
// Object tt= JSONObject.toBean(jo1);
// System.out.println(tt); } /**
* 使用registerPropertyExclusion达到前面的效果
*/
@Test
public void fun3(){
Teacher t=new Teacher(12,"guodaxia","gz1234");
JsonConfig config=new JsonConfig();
config.registerPropertyExclusion(Teacher.class, "password");
JSONObject jo=JSONObject.fromObject(t, config);
System.out.println(jo); } /**
* 测试使用自定义JSONBeanProcessor
* JsonBeanProcessor和实现JsonString很类似,返回一个代表原来目标对象的合法JSONObject
*
*/
@Test
public void fun4(){
JsonConfig config=new JsonConfig();
config.registerJsonBeanProcessor(Teacher.class,new JsonBeanProcessor() { public JSONObject processBean(Object bean, JsonConfig config) {
Teacher tea=(Teacher)bean;
return new JSONObject().element("id", tea.getId()).element("name", tea.getName());
}
});
Teacher t=new Teacher(12,"JSON","json");
System.out.println(JSONObject.fromObject(t,config)); } /**
* 自定义JsonValueProcessor
* 比如我们要控制JSON序列化过程中的Date对象的格式化以及数值的格式化,JsonValueProcessor是最好的选择
* 该方法可以用来处理数据,进行格式化操作等等
*/
@Test
public void fun5(){
Map<String,Object> map=new HashMap<String,Object>();
map.put("date", new Date());
map.put("dates", Arrays.asList(new Date()));
JsonConfig config=new JsonConfig();
config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
//自定义日期处理格式
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); /**
*处理单个Date对象
*/
public Object processObjectValue(String propertyName, Object date, JsonConfig config) {
return sdf.format(date);
} public Object processArrayValue(Object date, JsonConfig config) {
return sdf.format(date);
}
});
System.out.println(JSONObject.fromObject(map, config)); } }

最新文章

  1. [Xamarin] 從Xamarin中呼叫 *.jar 的 library - 呼叫篇 (转帖)
  2. 素数筛 poj 3518
  3. dede5.7前台插入恶意JS代码
  4. Codeforces Round #203 (Div. 2) A.TL
  5. C#开发COM组件供其他开发环境或工具调用介绍(转)
  6. IIS防止同一IP大量非法访问
  7. Java Load Properties 文件,定义message信息
  8. Web存储(Web Storage)介绍
  9. javascript 回调, 单线程执行
  10. LeetCode:1. Add Two Numbers
  11. 如何让局域网内的其他电脑访问本机的mysql
  12. 瑞芯微RKnanC芯片处理器介绍
  13. selenium+谷歌无头浏览器爬取网易新闻国内板块
  14. [Ubuntu]修改文件夹及所有子文件夹权限
  15. java--String equals方法
  16. js操作css样式,null和undefined的区别?
  17. vue2.0 组件和v-model
  18. 【实战】JBOSS反序列化Getshell
  19. 【android】使用RecyclerView和CardView,实现知乎日报精致布局
  20. excel表格的应用之简单的数据可视化

热门文章

  1. CentOS VSCode调试go语言出现:exec: &quot;gcc&quot;: executable file not found in PATH
  2. label 标签的用法,点label选中单选、复选框或文本框
  3. FreeSWITCH版本更新
  4. 【BZOJ2119】股市的预测 后缀数组+分块
  5. iptables的例子1
  6. 【python】-- 进程与线程
  7. win7 32位下载安装redis并安装php_redis扩展
  8. 我的Android进阶之旅------>Android SDK支持的配置标识符(有用的参考文件)
  9. TextView属性
  10. Cordova+FrameWork7开发简单教程