首页 > 解决方案 > Java中的自定义序列化

问题描述

目标:为 Java 对象创建一个 JSON 字符串。(以前我有一个使用 ISerializable -> GetObjectData 的 .NET 解决方案)。

由于我对 JAVA 很陌生,我对如何编写 Serializable 类有疑问。

创建了一个可序列化的类,并尝试通过自定义writeObject将其编写为 JSON,但在输出字符串中我得到了一些不需要的 ASCII 字符。

public class Employee implements Serializable  {
    private static final long serialVersionUID = 1L;
    private String serializeValueName;
    private int nonSerializeValueSalary;

    public String getSerializeValueName() {
        return serializeValueName;
    }

    public void setSerializeValueName(String serializeValueName) {
        this.serializeValueName = serializeValueName;
    }

    public int getNonSerializeValueSalary() {
        return nonSerializeValueSalary;
    }

    public void setNonSerializeValueSalary(int nonSerializeValueSalary) {
        this.nonSerializeValueSalary = nonSerializeValueSalary;
    }

    @Override
    public String toString() {
        return "Employee [serializeValueName=" + serializeValueName + "]";
    }

    private void writeObject(ObjectOutputStream oos) throws IOException {       
        oos.writeObject(String.format("{\"ValueName\":\"%s\",\"ValueSalary\":%s}", getSerializeValueName(), getNonSerializeValueSalary()));
    }

    public String serialize() {
        String serializedObject = "";
         try {
             ByteArrayOutputStream bo = new ByteArrayOutputStream();
             ObjectOutputStream so = new ObjectOutputStream(bo);
             writeObject(so);
             so.flush();
             serializedObject = bo.toString().substring(7);
         } catch (Exception e) {
             System.out.println(e);
         }      
        return serializedObject;        
    }
}

    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        Employee employeeOutput = null;
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        employeeOutput = new Employee();
        employeeOutput.setSerializeValueName("Aman");
        employeeOutput.setNonSerializeValueSalary(50000);
        String test = employeeOutput.serialize();
    }

当前输出以¬í为前缀,因此添加了子字符串方法来剪辑开头的字符。

预期输出:"{"ValueName":"Aman","ValueSalary":50000}"

标签: java

解决方案


推荐阅读