常用格式轉換整理(byte轉string, int轉string....)
阿新 • • 發佈:2018-11-08
1、String和int轉換
(1)Sting 轉為int
String str = "123";
try {
int a = Integer.parseInt(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
(2)int轉為String
String str = "123"; try { int b = Integer.valueOf(str).intValue() } catch (NumberFormatException e) { e.printStackTrace(); }
String str = "123";
int sb = String.valueOf(str);
2、Map轉String
在做Map<String,Object>資料存入redis和kafka時,需要使用這樣的轉換:json工具包
public static String map2Json(Map<?, ?> map) { try { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper.writeValueAsString(map); } catch (Exception e) { e.printStackTrace(); } return ""; }
JSONObject jsonobject = JSONObject.fromObject(str);
String msg = jsonObject.toString();
3、String和byte轉換
(1)string轉換為byte
String str = "abcdef";
byte b[] = str .getBytes();//String轉換為byte[]
(2)byte轉換為string
//b為byte[]
String t = new String(b);
持續整理中......