Java操作JSON数据(1)--JSON-lib操作JSON数据

JSON-lib是一个java库,用于将bean、映射、集合、java数组和XML转换为JSON,或将JSON转为beans和DynaBeans。JSON-lib最后的版本是2.4,更新时间是2010年12月14日,在以前的项目或系统中用的用的较多;本文简单介绍下其使用方法。文中所使用到的软件版本:Java 1.8.0_191、JSON-lib 2.4。

1、引入依赖

        <dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>

2、序列化

    public static String serialize() {
MyBean bean = new MyBean();
bean.setS("测试字符串");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -1);
bean.setD(calendar.getTime());
JsonConfig config = new JsonConfig();
//防止自包含
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
//Date类型转化
config.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
//过滤s3字段
config.setExcludes(new String[]{"s3"});
//过滤值为null的字段
config.setJsonPropertyFilter(new PropertyFilter() {
@Override
public boolean apply(Object arg0, String arg1, Object value) {
return value == null;
}
});
List<MyBean> list = new ArrayList<MyBean>();
list.add(bean);
Map<String, List<MyBean>> map = new HashMap<String, List<MyBean>>();
map.put("data", list);
JSON json = JSONSerializer.toJSON(map, config);
String result = json.toString();
System.out.println(json.toString());
return result;
}

3、反序列化

    public static void deserialize() {
try {
//处理日期类型
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[]{"yyyy-MM-dd HH:mm:ss"}));
String s = serialize();
Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
classMap.put("data", MyBean.class);
Map<String, List<MyBean>> map = (Map<String, List<MyBean>>) JSONObject.toBean(JSONObject.fromObject(s), Map.class, classMap);
System.out.println(map); //直接通过api获取相应数据
JSONObject obj = JSONObject.fromObject(s);
JSONArray data = obj.getJSONArray("data");
JSONObject bean = data.getJSONObject(0);
System.out.println(bean.getString("s"));
//...
} catch (Exception e) {
e.printStackTrace();
}
}

4、完整例子

package com.inspur.demo.json;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.JSONUtils;
import net.sf.json.util.PropertyFilter; /**
* JSON-lib操作JSON数据
*/
public class JsonLibCase {
/**
* 序列化
*/
public static String serialize() {
MyBean bean = new MyBean();
bean.setS("测试字符串");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -1);
bean.setD(calendar.getTime());
JsonConfig config = new JsonConfig();
//防止自包含
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
//Date类型转化
config.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
//过滤s3字段
config.setExcludes(new String[]{"s3"});
//过滤值为null的字段
config.setJsonPropertyFilter(new PropertyFilter() {
@Override
public boolean apply(Object arg0, String arg1, Object value) {
return value == null;
}
});
List<MyBean> list = new ArrayList<MyBean>();
list.add(bean);
Map<String, List<MyBean>> map = new HashMap<String, List<MyBean>>();
map.put("data", list);
JSON json = JSONSerializer.toJSON(map, config);
String result = json.toString();
System.out.println(json.toString());
return result;
} /**
* 反序列化
*/
public static void deserialize() {
try {
//处理日期类型
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[]{"yyyy-MM-dd HH:mm:ss"}));
String s = serialize();
Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
classMap.put("data", MyBean.class);
Map<String, List<MyBean>> map = (Map<String, List<MyBean>>) JSONObject.toBean(JSONObject.fromObject(s), Map.class, classMap);
System.out.println(map); //直接通过api获取相应数据
JSONObject obj = JSONObject.fromObject(s);
JSONArray data = obj.getJSONArray("data");
JSONObject bean = data.getJSONObject(0);
System.out.println(bean.getString("s"));
//...
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) {
serialize();
deserialize();
} static class DateJsonValueProcessor implements JsonValueProcessor {
@Override
public Object processArrayValue(Object value, JsonConfig arg1) {
return process(value);
} @Override
public Object processObjectValue(String key, Object value, JsonConfig arg2) {
return process(value);
}
private Object process(Object value) {
try {
if (value instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format((Date) value);
}
} catch (Exception e) {
e.printStackTrace();
}
return value == null ? "" : value.toString();
}
}
}

JsonLibCase

package com.inspur.demo.json;

import java.util.Arrays;
import java.util.Date; public class MyBean {
private String s = "字符串";
private String s2;
private String s3 = "字符串3";
private int i = 123;
private Integer i2;
private char c = '到';
private char[] c2 = new char[]{'a', 'b'};
private Date d = new Date();
private Date[] d2 = new Date[]{new Date(), new Date()};
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public String getS2() {
return s2;
}
public void setS2(String s2) {
this.s2 = s2;
}
public String getS3() {
return s3;
}
public void setS3(String s3) {
this.s3 = s3;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public Integer getI2() {
return i2;
}
public void setI2(Integer i2) {
this.i2 = i2;
}
public char getC() {
return c;
}
public void setC(char c) {
this.c = c;
}
public char[] getC2() {
return c2;
}
public void setC2(char[] c2) {
this.c2 = c2;
}
public Date getD() {
return d;
}
public void setD(Date d) {
this.d = d;
}
public Date[] getD2() {
return d2;
}
public void setD2(Date[] d2) {
this.d2 = d2;
}
@Override
public String toString() {
return "MyBean [s=" + s + ", s2=" + s2 + ", s3=" + s3 + ", i=" + i + ", i2=" + i2 + ", c=" + c + ", c2="
+ Arrays.toString(c2) + ", d=" + d + ", d2=" + Arrays.toString(d2) + "]";
}
}

MyBean

上一篇:MySQL数据库事务及其特性


下一篇:原生sql实现restful接口调用