如何编码地图 作为Base64字符串?

如何编码地图 作为Base64字符串?,第1张

如何编码地图 作为Base64字符

我的主要要求是:编码的字符串应尽可能短,并且仅包含拉丁字符或base64字母中的字符(不包括我的电话)。 没有其他要求。

使用Google Gson转换

Map
为JSON。使用
GZIPOutputStream
压缩JSON字符串。使用Apache
Commons
Codec
base64

base64OutputStream
将压缩字节编码为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);}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5615840.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存