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

无论出于何种原因,某些时候,我们需要对对象转为字符串的过程加以控制,最常见需求如数值格式化和日期格式化。JSON lib提供了JsonConfig对象,该对象能够深刻影响Java对象转成json字符串的行为。

增加忽略的属性

1. 第一种方式,实现JSONString接口的方法

package cn.ysh.studio.test;

import java.io.Serializable;

import net.sf.json.JSONObject;
import net.sf.json.JSONString; /**
*
* @author 杨胜寒
* @date 2013-6-27
*
*/
public class User implements JSONString, Serializable{ private static final long serialVersionUID = 1L;
private long id;
private String name;
private String password; public User(){} public User(Long id, String name, String password){
this.id = id;
this.name = name;
this.password = password;
} public User(String name, String password){
this.name = name;
this.password = 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;
} @Override
public String toJSONString() {
//return "{\"id\":" + this.id + ",\"name\":\"" + this.name + "\",\"password\":\""+ this.password +"\"}";
//忽略敏感字段password
return "{\"id\":" + this.id + ",\"name\":\"" + this.name + "\"}";
} public static void main(String[] args) {
User user = new User(12L, "JSON", "json");
System.out.println(JSONObject.fromObject(user).toString());
}
}

2.第二种方式,通过jsonconfig实例,对包含和需要排除的属性进行方便的添加或删除

package cn.ysh.studio.test;

import java.io.Serializable;

import net.sf.json.JSONObject;
import net.sf.json.JSONString;
import net.sf.json.JsonConfig; /**
*
* @author 杨胜寒
* @date 2013-6-27
*
*/
public class User { private long id;
private String name;
private String password; public User(){} public User(Long id, String name, String password){
this.id = id;
this.name = name;
this.password = password;
} public User(String name, String password){
this.name = name;
this.password = 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 static void main(String[] args) {
JsonConfig config = new JsonConfig();
config.setExcludes( new String[]{"password"});
User user = new User(12L, "JSON", "json");
System.out.println(JSONObject.fromObject(user, config).toString());
}
}

属性过滤器

使用propertyFilter可以允许同时对需要排除的属性和类进行控制,这种控制还可以是双向的,也可以应用到json字符串到java对象

JsonConfig config = new JsonConfig();
config.setJsonPropertyFilter(new PropertyFilter() { @Override
public boolean apply(Object source/* 属性的拥有者 */ , String name /*属性名字*/ , Object value/* 属性值 */) {
return source instanceof User && "password".equalsIgnoreCase(name);
}
});
User user = new User(12L, "JSON", "json");
System.out.println(JSONObject.fromObject(user, config).toString());

相对于上面的何种方式,如下的方式或许更为简便:

JsonConfig config = new JsonConfig();
config.registerPropertyExclusions(User.class, new String[]{"password"});
User user = new User(12L, "JSON", "json");
System.out.println(JSONObject.fromObject(user, config).toString());

自定义JsonBeanProcessor

JsonBeanProcessor和实现JsonString很类似,返回一个代表原来目标对象的合法JSONObject

JsonConfig config = new JsonConfig();
config.registerJsonBeanProcessor(User.class, new JsonBeanProcessor() { @Override
public JSONObject processBean(Object bean, JsonConfig config) {
User user = (User) bean;
return new JSONObject().element("id", user.getId()).element("name", user.getName());
}
});
User user = new User(12L, "JSON", "json");
System.out.println(JSONObject.fromObject(user, config).toString());

自定义JsonValueProcessor

比如我们要控制JSON序列化过程中的Date对象的格式化,以及数值的格式化,JsonValueProcessor是最好的选择。

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 simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); @Override
/**
* 处理单个Date对象
*/
public Object processObjectValue(String propertyName, Object date,JsonConfig config) {
return simpleDateFormat.format(date);
} @Override
/**
* 处理数组中的Date对象
*/
public Object processArrayValue(Object date, JsonConfig config) {
return simpleDateFormat.format(date);
}
});
System.out.println(JSONObject.fromObject(map, config).toString());

除了自定义日期格式外,还可以如法炮制,控制数值格式化、HTML内容转码等。

使用JsonConfig控制JSON lib序列化的更多相关文章

  1. json等序列化模块 异常处理

    今日学习内容如下: 1.序列化模块 什么叫序列化——将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化. 比如,我们在python代码中计算的一个数据需要给另外一段程序使用,那我们怎么给? 现 ...

  2. Newtonsoft.Json 的序列化与反序列化

    首先补充一点,Json.Net是支持序列化和反序列化DataTable,DataSet,Entity Framework和NHibernate的.我举例说明DataTable的序列化和反序列化.创建一 ...

  3. 【转】Newtonsoft.Json 的序列化与反序列化

    http://www.cnblogs.com/08shiyan/p/3464028.html 首先补充一点,Json.Net是支持序列化和反序列化DataTable,DataSet,Entity Fr ...

  4. Json.Net序列化和反序列化设置

    首先补充一点,Json.Net是支持序列化和反序列化DataTable,DataSet,Entity Framework和NHibernate的.我举例说明DataTable的序列化和反序列化.创建一 ...

  5. Json.Net系列教程 3.Json.Net序列化和反序列化设置

    原文 Json.Net系列教程 3.Json.Net序列化和反序列化设置 上节补充 首先补充一点,Json.Net是支持序列化和反序列化DataTable,DataSet,Entity Framewo ...

  6. Json常用序列化工具包大比拼

    一.前言 Json已成为计算机编程中最常用的数据传输和存储格式之一,所以对Json的序列化和反序列化工具的选择也是互联网系统中比较重要的环节,尤其在高并发下的执行效率,可能会直接影响系统的吞吐率.本文 ...

  7. SpringBoot系列: Json的序列化和反序列化

    ============================= 控制 json 序列化/反序列化=============================1. @JsonIgnoreProperties的 ...

  8. Jackson 通过自定义注解来控制json key的格式

    Jackson 通过自定义注解来控制json key的格式 最近我这边有一个需求就是需要把Bean中的某一些特殊字段的值进行替换.而这个替换过程是需要依赖一个第三方的dubbo服务的.为了使得这个转换 ...

  9. [.net 面向对象程序设计进阶] (12) 序列化(Serialization)(四) 快速掌握JSON的序列化和反序列化

    [.net 面向对象程序设计进阶] (12) 序列化(Serialization)(四) 快速掌握JSON的序列化和反序列化 本节导读: 介绍JSON的结构,在JS中的使用.重点说明JSON如何在.N ...

随机推荐

  1. JDK动态代理实现机制

    =========================================== 原文链接: JDK动态代理实现机制   转载请注明出处! =========================== ...

  2. JavaWeb之cookie

    什么叫做会话 ? 用户从打开一个浏览器开始,浏览器网站,到关闭浏览器的整个过程叫做一次会话! 每个用户与服务器进行交互的过程中,各自会有一些数据,程序要想办法保存每个用户的数据. 例如:用户点击超链接 ...

  3. 手机自动化测试:Appium代码之Logger

    手机自动化测试:Appium代码之Logger   poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.poptest推出手机自动化测 ...

  4. 测试开发Python培训:抓取新浪微博抓取数据-技术篇

    测试开发Python培训:抓取新浪微博抓取数据-技术篇   poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.在poptest的se ...

  5. 这辈子只能碰到一次! 记一次SSL无故被撤消!

    SSL证书刚更新一切都那么正常, 突然有一天网站不能访问了, Chrome浏览器提示有风险, 没有继续访问链接,没有,没有, 重要的事情说三遍, 于是乎赶紧加班查原因, 发展浏览器报的错误是证书撤消( ...

  6. SQL使用视图的优缺点

    视图是为了查询方便!也就是多个表的总结!但是不能对视图增删改! 在做数据库开发中使用视图的优点有: 1.视图的好处就是在你做复杂的查询逻辑时可以简化你的思考过程. 2.用视图可以隐藏一定的信息,用过滤 ...

  7. Android批量验证渠道、版本号

    功能:可校验单个或目录下所有apk文件的渠道号.版本号使用说明:1.copy需要校验的apk文件到VerifyChannelVersion目录下2.双击运行VerifyChannelVersion.b ...

  8. npm安装

    淘宝镜像http://npm.taobao.org/ $ npm install -g cnpm --registry=https://registry.npm.taobao.org mac下 sud ...

  9. 在Centos中yum安装和卸载软件的使用方法

    安装一个软件时 yum -y install httpd 安装多个相类似的软件时 yum -y install httpd* 安装多个非类似软件时 yum -y install httpd php p ...

  10. [Python]再学 socket 之非阻塞 Server

    再学 socket 之非阻塞 Server 本文是基于 python2.7 实现,运行于 Mac 系统下 本篇文章是上一篇初探 socket 的续集, 上一篇文章介绍了:如何建立起一个基本的 sock ...