欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

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

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);
            //obj.getjsonarray(key)
            //obj.getjsonobject(key)
            //obj.getstring(key);
        } 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.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);
            //obj.getjsonarray(key)
            //obj.getjsonobject(key)
            //obj.getstring(key);
        } 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();
        }
    }
}
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) + "]";
    }
}