总结一下目前手头的项目~发现不少知识点的盲区,如下。做个小笔记方便以后复用。
blob,base64互转
最开始编码解码用的是原生base64,encode因为直接从数据库拿到的blob传进入,不允许强转,遂用流重写之;
而decode存入数据库图片打开有问题,就也换了。查了好久没查到导致的原因,总之它可以工作了。
return Base64.decodeBase64(base64Str);
return Base64.encodeBase64String(bytes);
/**
* blob转base64
* @param blob
* @return
*/
public static String convertBlobToBase64String(Blob blob) {
String result = "";
if(null != blob) {
try {
InputStream msgContent = blob.getBinaryStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[100];
int n = 0;
while (-1 != (n = msgContent.read(buffer))) {
output.write(buffer, 0, n);
}
result =new BASE64Encoder().encode(output.toByteArray()) ;
output.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}else {
return null;
}
}
/**
* base64转blob
* @param str
* @return
*/
public static byte[] transformBase64(String str) {
BASE64Decoder decode = new BASE64Decoder();
byte[] b = null;
try {
b = decode.decodeBuffer(str);
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
私有方法的测试
@Test
public void test_方法名(){
try{
//创建类
ServiceClass service = new ServiceClass();
//指定方法
Method method = ServiceClass.class.getDeclaredMethod("方法名", 参数类型.class);
//允许反射调用私有方法
method.setAccessible(true);
//执行
System.out.println(method.invoke(service, 参数···));
}catch(Exception ex){
ex.printStackTrace();
}
}
GSon的坑
用GSon处理json数据发现这个工具有些比较坑的地方。
比如转换“201609121830”这样的时间字段,会变成科学计数法,很崩溃。只有用new BigDecimal((Double) paramMap.get("DATE")).toString()这样的方法,让它正常显示。
再比如,转换时遇上空字段直接抛错,可以重写原生的一些方法来避免,但不知道为什么调试的时候总是进不去这个方法,网上的教材也是大同小异的,调用方法也很简单,看不出什么错误。遂崩溃,换了Jackson~
/**
* JSON转HashMap
* @param jsonStr
* @return
* @throws Exception
*/
public static Map<String, Map<String, Object>> JSON2HashMap(String jsonStr) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Map<String, Object>> maps = objectMapper.readValue(jsonStr, Map.class转换的格式);
return maps;
}
map转json也很简单
ObjectMapper mapper =
new
ObjectMapper();
String json = mapper.writeValueAsString(map);