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

java对象序列化与反序列化的默认格式和json格式使用示例

程序员文章站 2024-02-22 11:38:10
默认格式 复制代码 代码如下:public class myclass implements serializable{...} 序列化:复制代码 代码如下:objec...

默认格式

复制代码 代码如下:

public class myclass implements serializable{
...}

序列化:

复制代码 代码如下:

objectoutputstream output = new objectoutputstream(new fileoutputstream(outputpath));
output.writeobject(myobject);

反序列化:

复制代码 代码如下:

objectinputstream input = new objectinputstream(new fileinputstream(inputpath));
return (myclass)input.readobject();

json格式

使用jackson包。jackson是一个效率非常高的java json包。文档和下载见官网。

序列化

复制代码 代码如下:

objectmapper mapper = new objectmapper();
mapper.writevalue(new file(outputpath), myobject);

反序列化:

复制代码 代码如下:

return mapper.readvalue(new file(outputpath), myclass.class);

完整测试代码

复制代码 代码如下:

import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.objectinputstream;
import java.io.objectoutputstream;
import java.io.serializable;
import java.util.arraylist;

import com.fasterxml.jackson.core.jsongenerationexception;
import com.fasterxml.jackson.core.jsonparseexception;
import com.fasterxml.jackson.databind.jsonmappingexception;
import com.fasterxml.jackson.databind.objectmapper;

public class zoo implements serializable {

    private static final long serialversionuid = 1l;
    private static objectmapper mapper = new objectmapper();

    public static int maxanimalcount;
    public arraylist<string> animals;

    public zoo() {
        animals = new arraylist<string>();
    }

    public static void setmax(int max){
        maxanimalcount = max;
    }

    /**
     * add an animal to animals array.
     * @param animalname
     */
    public void addanimal(string animalname){
        if (animals.size() < maxanimalcount)
            animals.add(animalname);
    }

    @override
    public string tostring(){
        return "zoo: \n animals: " + animals.tostring() +
                "\n maxanimalcount: " + maxanimalcount + "\n";
    }

    /**
     * output standard serialization to file at logpath.
     * @param logpath
     */
    public void serializetolog(string logpath) {
        objectoutputstream output = null;
        try
        {
            output = new objectoutputstream(
                    new fileoutputstream(logpath));
            output.writeobject(this);
        } catch(exception e) {
            e.printstacktrace();
        } finally {
            try {
                output.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }

    /**
     * output json serialization(using jackson) to file at logpath.
     * @param logpath
     */
    public void serializejsontolog(string logpath){

        try {
            mapper.writevalue(new file(logpath), this);
        } catch (jsongenerationexception e) {
            e.printstacktrace();
        } catch (jsonmappingexception e) {
            e.printstacktrace();
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    /**
     * standard deserialize a zoo instance from file at logpath.
     * @param logpath
     * @return deserialized zoo instance
     */
    public static zoo deserializefromlog(string logpath) {
        objectinputstream input = null;
        try
        {
            input =new objectinputstream(
                    new fileinputstream(logpath));
            return (zoo)input.readobject();
        } catch(exception e) {
            e.printstacktrace();
        } finally {
            try {
                input.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }

        return null;
    }

    /**
     * json deserialize a zoo instance from file at logpath.
     * @param logpath
     * @return json deserialized zoo instance
     */
    public static zoo deserializejsonfromlog(string logpath){
        try {
            return mapper.readvalue(new file(logpath), zoo.class);
        } catch (jsonparseexception e) {
            e.printstacktrace();
        } catch (jsonmappingexception e) {
            e.printstacktrace();
        } catch (ioexception e) {
            e.printstacktrace();
        }

        return null;
    }
}

class zooserializetest {
    public static void main(string[] args) {
        zoo zoo1 = new zoo();
        zoo.setmax(100);
        zoo1.addanimal("hamster");
        zoo1.addanimal("sheep");

        zoo1.serializetolog("zoo1.log");

        zoo zoo2 = new zoo();
        zoo.setmax(200);
        zoo2.addanimal("tiger");

        zoo2.serializetolog("zoo2.log");

        zoo.setmax(300);

        //deserialization
        zoo1 = zoo.deserializefromlog("zoo1.log");
        zoo2 = zoo.deserializefromlog("zoo2.log");

        system.out.println("zoo1: \n" + zoo1);
        system.out.println("zoo2: \n" + zoo2);

        //serialize to json
        zoo1.serializejsontolog("zoo1.json");
        zoo1 = zoo.deserializejsonfromlog("zoo1.json");

        system.out.println("zoo1 from json: \n" + zoo1);
    }
}