我喜欢将字符串的java映射编码为一个base64编码的字符串。编码的字符串将被传输到远程端点,并且可能被不友好的人操纵。所以最糟糕的事情应该是无效的键,值-元组,但不应该带来任何其他的安全风险。
示例:
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();
谢谢,
发布于 2010-02-08 20:58:53
我的主要要求是:编码的字符串应该尽可能短,并且只包含拉丁字符或base64字母表中的字符(不是my
)。没有其他要求。
使用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);
}
发布于 2010-02-08 20:47:28
另一种可能的方式是使用JSON,这是一个非常轻量级的库。然后,编码将如下所示:
JSONObject jso = new JSONObject( map );
String encoded = new String(Base64.encodeBase64( jso.toString( 4 ).toByteArray()));
发布于 2010-02-08 20:19:05
您的解决方案起作用了。唯一的另一种方法是自己序列化映射(迭代键和值)。这意味着您必须确保正确处理所有大小写(例如,如果您将值作为key=value
传输,则必须找到一种方法在键/值中允许=
,并且必须以某种方式分隔这些对,这意味着您还必须在名称中允许此分隔字符,等等)。
总而言之,这很难正确,很容易出错,并且需要更多的代码和令人头疼的东西。另外,不要忘记,您必须在解析器(接收器端)中编写大量错误处理代码。
https://stackoverflow.com/questions/2221413
复制相似问题