com.alibaba.fastjson.com
带转义和引号的字符串转换:
//带有转义的那种字符串,不带转义的那种会报错
String jsonStr="{\"name\":\"zhangsan\",\"age\":\"123\"}";
JSONObject jsonObject=JSONObject.parseObject(jsonStr);
不带转义和引号的字符串转换:
//不带转义的json格式字符串转换{success=0, msgid=1000001, msg=appkey错误或不存在}
String str="{success=0, msgid=1000001, msg=appkey错误或不存在}";
String input = StringUtils.substringBetween(str, "{", "}"); // substringBetween 截取两个标签之间的文本 input="success=0, msgid=1000001, msg=appkey错误或不存在"
Map<String, String> map = Splitter.on(",").withKeyValueSeparator("=").split(input); // 指定以,为连接的input字符串,withKeyValueSeparator 指定键值对中的分隔符
System.out.println(JSON.toJSONString(map)); // {"success":"0"," msgid":"1000001"," msg":"appkey错误或不存在"}
不带引号的字符串,需要用到guava分割后转:https://blog.csdn.net/chinabestchina/article/details/89290494
JSONObject jsonObject=JSONObject.parseObject(jsonStr);
//获取key为name的值
String name=jsonObject.get("name");
jsonStr为JSON对象,Employee 为要转为的对象
Employee emp=JSONObject.parseObject(jsonStr, Employee.class);
这个方法会出现一个问题,某些值会丢失。
替代方法,先转为Map,然后直接通过get取值
Map<String, Object> map = JSON.parseObject(json, Map.class);
map.get("name");
JSONObject json=(JSONObject) JSONObject.toJSON(res);
List<User> users= new ArrayList<>();
for (int i=1;i<=100;i++){
User user=new User();
user.setUserName("张"+i);
user.setPassWord("pwd"+i);
users.add(user);
}
String strs= JSON.toJSONString(users);
Map<String,String> map = new HashMap<String,String>();
map.put("name","zhangsan");
map.put("age","123");
map.put("sex","1");
String json=JSON.toJSONString(map); //map先转string
JSONObject jsonObject = JSONObject.parseObject(json); //string再转JSONObject
System.out.println(jsonObject); // {"sex":"1","name":"zhangsan","age":"123"}
Map map1=JSON.parseObject(JSON.toJSONString(jsonObject)); //json先转string,再转Map
map1.forEach((k,v)->{
System.out.println(k+":"+v);
});
User user = new User("张三", 20);
String jsonUser = new ObjectMapper().writeValueAsString(user);
System.out.println(jsonUser);
使用JSONObject的toString时,多了斜杠\
,直接使用JSONObject.parse
转一下,
使用JSONObject.parse
后
List<User> users = user.toJavaList(User.class);
//list先转JSON,再通过JSONArray的parseArray转成JSONArray
JSONArray.parseArray(JSON.toJSONString(list))
//providers="[{"bdid":"4ee415092e1344a18e1864b2fe8ebbe0","winId":"e8b40032886a4e7a8ae33c7f17343e99","remark":""},{"bdid":"840df7c0b9114bc3b17359e69b91a661","winId":"9e600a6dc0604909a943946b3ca7c278","remark":""}]"
JSONArray jsonArray = JSONArray.parseArray(providers);
// seal2=[11,12,13]
JSONArray seal2 = (JSONArray) map.get("seal2");
System.out.println(seal2.toString());
//或者直接toString
System.out.println(map.get("seal"+i).toString());
//String sealStr={"seal0":["1"],"seal1":["4","5"],"seal2":["11","12","13"]}
Map map= (Map) JSON.parse(sealStr);
map.forEach((k,v)->{
System.out.println(k+"--------------------"+v);
});