Java中的JsonConfig详解
程序员文章站
2022-07-12 15:53:31
...
JSON lib能够将Java对象转成json格式的字符串,也可以将Java对象转换成xml格式的文档,同样可以将json字符串转换成Java对象或是将xml字符串转换成Java对象。
无论出于何种原因,某些时候,我们需要对对象转为字符串的过程加以控制,最常见需求如数值格式化和日期格式化。JSON lib提供了JsonConfig对象,该对象能够深刻影响Java对象转成json字符串的行为。
1.手动方法
package lcc.json.test;
import java.util.Date;
public class User {
private long id;
private String name;
private String password;
private Date regtime;
public String toJsonString() {
return "{\"id\":" + this.id + ",\"name\":\"" + this.name + ",\"password\":\"" + this.password + ",\"regtime\":\"" + this.regtime + "\"}";
}
public User(long id, String name, String password, Date regtime) {
super();
this.id = id;
this.name = name;
this.password = password;
this.regtime = regtime;
}
}
package lcc.json.test;
import java.util.Date;
public class Mytest {
public static void main(String[] args) {
// TODO Auto-generated method stub
User user = new User(12, "JSON", "json",new Date(System.currentTimeMillis()));
System.out.println(user.toJsonString());
}
}
运行结果
{"id":12,"name":"JSON,"password":"json,"regtime":"Thu Feb 01 09:30:52 CST 2018"}
这个是手动方法,如果假设我们需要把时间格式是2018-05-09这样的格式呢?我们需要修改toJsonString方法
public String toJsonString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return "{\"id\":" + this.id + ",\"name\":\"" + this.name + ",\"regtime\":\"" + sdf.format(this.regtime) + "\"}";
}
打印结果:
{"id":12,"name":"梁川川,"regtime":"2018-02-01"}
如果里面有null值呢?我们又不知道是那个是空值,那么就比较麻烦了,借助JsonConfig可以很好的帮助我们
1. 第一种方式,实现JSONString接口的方法
package lcc.json.test;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JSONString;
public class User implements JSONString, Serializable{
private long id;
private String name;
private String password;
private Date regtime;
public String toJSONString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return "{\"id\":" + this.id + ",\"name\":\"" + this.name + "\",\"regtime\":\"" + sdf.format(this.regtime) + "\"}";
}
public User(long id, String name, String password, Date regtime) {
super();
this.id = id;
this.name = name;
this.password = password;
this.regtime = regtime;
}
}
package lcc.json.test;
import java.util.Date;
import net.sf.json.JSONObject;
public class Mytest {
public static void main(String[] args) {
User user = new User(12, "梁川川", "json",new Date(System.currentTimeMillis()));
System.out.println(JSONObject.fromObject(user).toString());
}
}
比较手工方法和这个方法,是不是感觉还麻烦了一点?,其实我刚刚开始也是这么觉得的,但是时间上是,完善了一点,比如,在手工方法中,看打印结果
手工
手工:{"id":12,"name":"梁川川,"regtime":"2018-02-01"}
继承:{"id":12,"name":"梁川川","regtime":"2018-02-01"}
有一点点区别,”梁川川 与 “梁川川” 一个引号的问题,在手工方法中,我们错误的json完全需要我们自己去判断,继承则会帮我们检查,否则,会报错。
Exception in thread "main" net.sf.json.JSONException: Expected a ',' or '}' at character 23 of {"id":12,"name":"梁川川,"regtime":"2018-02-01"}
at net.sf.json.util.JSONTokener.syntaxError(JSONTokener.java:499)
这种方法感觉也有点麻烦
2.第二种方式,通过jsonconfig实例,对包含和需要排除的属性进行方便的添加或删除
package lcc.json.test;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JSONString;
public class User {
private long id;
private String name;
private String password;
private Date regtime;
public User(long id, String name, String password, Date regtime) {
super();
this.id = id;
this.name = name;
this.password = password;
this.regtime = regtime;
}
... 省略get set方法
}
public class Mytest {
public static void main(String[] args) {
JsonConfig config = new JsonConfig();
config.setExcludes( new String[]{"password"});
User user = new User(12, "梁川川", "json",new Date(System.currentTimeMillis()));
System.out.println(JSONObject.fromObject(user, config).toString());
}
}
运行结果
{"id":12,"name":"梁川川","regtime":{"date":1,"day":4,"hours":9,"minutes":55,"month":1,"seconds":49,"time":1517450149883,"timezoneOffset":-480,"year":118}}
JsonValueProcessor
这里时间明显不好看,如果转化成2018-05-09格式呢?我们需要使用JsonValueProcessor
Example:
java里面时间类型转换成json数据就成这样了:
"createTime":{"date":30,"day":3,"hours":15,"minutes":14,"month":3,"nanos":0,"seconds"
:38,"time":1209539678000,"timezoneOffset":-480,"year":108}
期望的结果是"yyyy-mm--dd"
解决方案:使用jsonConfig即可
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
修改main方法
package lcc.json.test;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
public class Mytest {
public static void main(String[] args) {
JsonConfig config = new JsonConfig();
config.setExcludes( new String[]{"password"});
User user = new User(12, "梁川川", "json",new Date(System.currentTimeMillis()));
config.registerJsonValueProcessor(java.util.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(user, config).toString());
}
}
运行结果
劳资感觉更加麻烦了,但是这个是自定义的,我们可以随便使用,可以对所有的类型字段自定义操作
setJsonPropertyFilter 和 PropertyFilter 属性过滤
如何过滤json中的一些数据呢?比如过滤空值
jsonConfig = new JsonConfig();
PropertyFilter filter = new PropertyFilter() {
@Override
public boolean apply(Object source, String name, Object value) {
if (value == null) {
return true;
}
return false;
}
};
jsonConfig.setJsonPropertyFilter(filter);