【问题标题】:How to write serializable object to String without writing to file?如何在不写入文件的情况下将可序列化对象写入字符串?
【发布时间】:2021-11-25 11:54:12
【问题描述】:

我想将一个类对象写入字符串,然后再次从中创建一个对象。 我在网上搜索,但我发现的只是将一个对象写入文件,但我想写入字符串,而不是文件。

下面是写入文件的示例,我想写入字符串或类似的对象而不是文件。

some_class implements serializable {
    ...
}

FileOutputStream f = new FileOutputStream(new File("myObjects.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);

// Write objects to file
o.writeObject(object1);

o.close();
f.close();

FileInputStream fi = new FileInputStream(new File("myObjects.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);

// Read objects
some_class object2 = (some_class) oi.readObject();

oi.close();
fi.close();

请帮忙。

【问题讨论】:

  • 您是什么意思:“将其写入字符串”?将其存储在 String 变量中?
  • 覆盖默认的toString 方法?
  • 是的,这意味着将其存储在字符串变量中而不写入文件。 @Stultuske
  • 你没有。 String 不是二进制数据的容器。您可以使用byte[]

标签: java serialization serializable objectoutputstream


【解决方案1】:

这是一种方式:

try 
{
    // To String
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(bos);
    os.writeObject(object1);
    String serializedObject1 = bos.toString();
    os.close();

    // To Object 
    ByteArrayInputStream bis = new ByteArrayInputStream(serializedObject1.getBytes());
    ObjectInputStream oInputStream = new ObjectInputStream(bis);
    YourObject restoredObject1 = (YourObject) oInputStream.readObject();            

    oInputStream.close();
} catch(Exception ex) {
    ex.printStackTrace();
}

我更喜欢Base64 方式。

这将是一个编码示例:

private static String serializableToString( Serializable o ) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(o);
        oos.close();
        return Base64.getEncoder().encodeToString(baos.toByteArray()); 
    }

这是一个解码的例子:

 private static Object objectFromString(String s) throws IOException, ClassNotFoundException 
   {
        byte [] data = Base64.getDecoder().decode(s);
        ObjectInputStream ois = new ObjectInputStream( 
                                        new ByteArrayInputStream(data));
        Object o  = ois.readObject();
        ois.close();
        return o;
   }

【讨论】:

    【解决方案2】:

    将对象序列化为字符串的最佳方式,反之亦然,您应该将对象转换为 JSON 字符串并编码为 base64。并使用 GSON(开源谷歌提供 java 库)获取对象解码 base64 并转换为对象

    class foo{ String name, email;
    //setter getter
    }
    

    将对象转换为 base64 JSON

    public static String convertToJson(Object o){
           String result=new Gson().toJson(o);
           return Base64.getEncoder().encodeToString(result);
    }
    

    //读取base64

    public static <T> T convertJsonToObject(String base64Object,Class<T> classOfT){
        Gson gson = new Gson();
        return gson.fromJson(new InputStreamReader(new ByteArrayInputStream(Base64.getDecoder().decode(base64Object))),classOfT);
    }
    
    public static void main(String[] args) {
        foo obj=new foo("jhon","jhon@gamil.com");
        String json=convertToJson(foo);
        System.out.println(json);
        foo obj_fromJson=convertJsonToObject(json,foo.class);
        System.out.println(obj_fromJson.getName());
    }
    

    【讨论】:

    • 实际上,我必须实现'serializable',因为它是已经使用'serializable'的库的一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多