java String字符串转换成json格式
String里面有很多的转义字符,不是一个正确的JSON字符串,不能直接序列化
示例1:
"{\"id\":\"1\",\"name\":\"小王\",\"password\":\"123456\"}"
解决方法
String data01 = "{\"id\":\"1\",\"name\":\"小王\",\"password\":\"123456\"}";
System.out.println("data01:" + data01);
String data02 = JSON.toJSONString(data01); // 序列化为JSON字符串
System.out.println("data02:" + data02);
String data03 = data02.replace("\\", ""); //通过 replace 去掉斜杠
System.out.println("data03:" + data03);
String data04 = data03.substring(1, data03.length() - 1); //去掉首尾的引号
System.out.println("data04:" + data04);
Map map = JSON.parseObject(data04, Map.class);
System.out.println(map.get("name"));
示例2:
"[
{\"FileName\":\"20210621084313_1.jpg\",\"FileSize\":41339,\"ExtensionName\":\".jpg\",\"FileId\":\"d4b0451866cd49b28b4494a07d38d1fb\"},
{\"FileName\":\"20210621084337_1.jpg\",\"FileSize\":32569,\"ExtensionName\":\".jpg\",\"FileId\":\"65989c8c4ec94a6f82fce0608ca02433\"}
]"
解决方法
String data01 = "[{\"FileName\":\"20210621084313_1.jpg\",\"FileSize\":41339,\"ExtensionName\":\".jpg\",\"FileId\":\"d4b0451866cd49b28b4494a07d38d1fb\"}, {\"FileName\":\"20210621084337_1.jpg\",\"FileSize\":32569,\"ExtensionName\":\".jpg\",\"FileId\":\"65989c8c4ec94a6f82fce0608ca02433\"}]"
System.out.println("data01:" + data01);
String data02 = JSON.toJSONString(data01); // 序列化为JSON字符串
System.out.println("data02 :" + data02 );
String data03 = data02.replace("\\", ""); //通过 replace 去掉斜杠
System.out.println("data03 :" + data03 );
String data04 = data03.substring(2, data03.length() - 2); //去掉首尾的引号
System.out.println("data04:" + data04);
List<Map<String,Object>> list = JSON.parseObject(data04, List.class);