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)); } }

json-lib的一些过滤操作的更多相关文章

  1. Atitit.json类库的设计与实现 ati json lib

    Atitit.json类库的设计与实现 ati json lib 1. 目前jsonlib库可能有问题,可能版本冲突,抛出ex1 2. 解决之道:1 2.1. 自定义json解析库,使用多个复合的js ...

  2. 如何对Backbone.Collection进行过滤操作

    首先我想说的是这篇文章的题目起的很怪,因为我不知道起个什么名字比较好.渲染列表是我们应用中最常见的操作了吧,在运用Backbone的应用中,我们一般会把列表作为一个Collcetion,然后指定一个V ...

  3. @JSON(serialize=false),过滤不需要的变量

    @JSON(serialize=false),过滤不需要的变量   在用struts2返回json类型的数据时,json会自动转换需要转换成json形式的变量,如果哪个变量不需要的话,则可以在该变量的 ...

  4. Json lib集成stucts2的使用方法 抛出 NestableRuntimeException异常的解决办法

    首先贴出struts 2.3.16需要导入的包 因为使用的是2.3 版本,必须要导入这个包,否则会报java.lang.NoClassDefFoundError: org/apache/commons ...

  5. 使用JsonConfig控制JSON lib序列化

    将对象转换成字符串,是非常常用的功能,尤其在WEB应用中,使用 JSON lib 能够便捷地完成这项工作.JSON lib能够将Java对象转成json格式的字符串,也可以将Java对象转换成xml格 ...

  6. 微信小程序 WXS实现json数据需要做过滤转义(filter)

    前言 最近有在做小程序开发,在开发的过程中碰到一点小问题,描述一下先. 本人在职的公司对于后台获取的 json 数据需要做过滤转义的很多,不同的状态码会对应不同的文字,但是在微信小程序中又没有类似 v ...

  7. Trident的过滤操作

    1.过滤操作 只是判断某个tuple是否保留 无需跨网络,无需跨分区 不会改变tuple的结构,只是改变tuple的数量 2.需求 过滤掉不是订单的tuple. 其中订单中包含“IBEIfeng.gi ...

  8. stark组件之过滤操作【模仿Django的admin】

    一.先看下django的admin是如何实现过滤操作 首先在配置类中顶一个list_filter的列表,把要过滤的字段作为元素写i进去就可以了 class testbook(admin.ModelAd ...

  9. Fiddler过滤操作

    Fidller,不做过多的简介,其中的过滤操作肯定是绕不过去的.直接上图.

  10. 【SQL必知必会笔记(3)】SELECT语句的WHERE子句数据过滤操作

    上个笔记主要介绍了利用SELECT语句检索单个/多个/所有列,并利用DISTINCT关键字检索具有唯一性的值.利用LIMIT/OFFSET子句限制结果:以及利用ORDER BY子句排序检索出的数据,主 ...

随机推荐

  1. &lt;C#入门经典&gt;学习笔记1之初识C#

    序言 选择< C#入门经典第五版>作为自学书籍,以此记录学习过程中的笔记与心得. C#简单介绍 1. C#是一种块结构的语言 2. C#区分大写和小写 C#变量 C#的变量定义与C语言相似 ...

  2. unity回调函数范例

    using System.Collections; using System.Collections.Generic; using UnityEngine; public class callback ...

  3. Laravel开发:Laravel核心——Ioc服务容器源码解析(服务器绑定)

    服务容器的绑定 bind 绑定 bind 绑定是服务容器最常用的绑定方式,在 上一篇文章中我们讨论过,bind 的绑定有三种: 绑定自身 绑定闭包 绑定接口 今天,我们这篇文章主要从源码上讲解 Ioc ...

  4. 基于jquery的bootstrap在线文本编辑器插件Summernote (转)

    Summernote是一个基于jquery的bootstrap超级简单WYSIWYG在线编辑器.Summernote非常的轻量级,大小只有30KB,支持Safari,Chrome,Firefox.Op ...

  5. lua例子(进出栈)

    #include <stdio.h> extern "C" { #include "lua-5.2.2/src/lauxlib.h" #includ ...

  6. [精]poj2724

    Purifying Machine Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 5027   Accepted: 1455 ...

  7. 【BZOJ4004】[JLOI2015]装备购买 贪心+高斯消元

    [BZOJ4004][JLOI2015]装备购买 Description 脸哥最近在玩一款神奇的游戏,这个游戏里有 n 件装备,每件装备有 m 个属性,用向量zi(aj ,.....,am) 表示 ( ...

  8. Python中的TCP编程,实现客户端与服务器的聊天(socket)

    参考大神blog:自己再写一个 https://blog.csdn.net/qq_31187881/article/details/79067644

  9. 九度OJ 1255:骰子点数概率 (递归、DP)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:316 解决:29 题目描述: 把n个骰子扔在地上,所有骰子朝上一面的点数之和为S.输入n,打印出S的所有可能的值出现的概率. 输入: 输入包 ...

  10. iOS绘图CGContextRef详解

    转自:http://blog.csdn.net/u014286994/article/details/51333118 /* CoreGraphics - CGContext.h */ /** Gra ...