gpt4 book ai didi

java - 如何将 Map 编码为 Base64 字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:32 24 4
gpt4 key购买 nike

我喜欢将字符串的 java 映射编码为单个 base 64 编码字符串。编码后的字符串将被传输到远程端点,并可能被不友善的人操纵。因此,应该发生的最糟糕的事情是无效的键值元组,但不应将任何其他安全风险放在一边。

例子:

Map<String,String> map = ...
String encoded = Base64.encode(map);

// somewhere else
Map<String,String> map = Base64.decode(encoded);

是的,必须是Base64。 Not like that or that or any other of these .是否有现有的轻量级解决方案(首选 Single Utils-Class)?还是我必须自己创建?

还有比这更好的吗?

// marshalling
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(map);
oos.close();
String encoded = new String(Base64.encodeBase64(baos.toByteArray()));

// unmarshalling
byte[] decoded = Base64.decodeBase64(encoded.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
ObjectInputStream ois = new ObjectInputStream(bais);
map = (Map<String,String>) ois.readObject();
ois.close();

谢谢,

最佳答案

my primary requirements are: encoded string should be as short as possible and contain only latin characters or characters from the base64 alphabet (not my call). there are no other reqs.

使用Google GsonMap 转换为 JSON .使用 GZIPOutputStream压缩 JSON 字符串。使用 Apache Commons Codec Base64Base64OutputStream将压缩字节编码为 Base64 字符串。

启动示例:

public static void main(String[] args) throws IOException {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");

String serialized = serialize(map);
Map<String, String> deserialized = deserialize(serialized, new TypeToken<Map<String, String>>() {}.getType());

System.out.println(deserialized);
}

public static String serialize(Object object) throws IOException {
ByteArrayOutputStream byteaOut = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = null;
try {
gzipOut = new GZIPOutputStream(new Base64OutputStream(byteaOut));
gzipOut.write(new Gson().toJson(object).getBytes("UTF-8"));
} finally {
if (gzipOut != null) try { gzipOut.close(); } catch (IOException logOrIgnore) {}
}
return new String(byteaOut.toByteArray());
}

public static <T> T deserialize(String string, Type type) throws IOException {
ByteArrayOutputStream byteaOut = new ByteArrayOutputStream();
GZIPInputStream gzipIn = null;
try {
gzipIn = new GZIPInputStream(new Base64InputStream(new ByteArrayInputStream(string.getBytes("UTF-8"))));
for (int data; (data = gzipIn.read()) > -1;) {
byteaOut.write(data);
}
} finally {
if (gzipIn != null) try { gzipIn.close(); } catch (IOException logOrIgnore) {}
}
return new Gson().fromJson(new String(byteaOut.toByteArray()), type);
}

关于java - 如何将 Map<String,String> 编码为 Base64 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2221413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com