/** * 若成功往往有data数据 * 示例: * UserBase userBase = new UserBase(); * userBase.setUserName("李昱鑫"); * userBase.setUserPwd("123"); * userBase.setUserAge(100); * return ResponseUtil.okWithData(userBase); 对应结果1: * return ResponseUtil.okWithData(objectMapper.writeValueAsString(userBase)); 对应结果2: * * 结果1:{"flag":true,"code":0,"msg":"ok","data":{"userName":"李昱鑫","userPwd":"123","userAge":100},"tkexp":false,"hurl":null,"time":"2019-12-31 08:19:25"} * 结果2:{"flag":true,"code":0,"msg":"ok","data":"{"userName":"李昱鑫","userPwd":"123","userAge":100}","tkexp":false,"hurl":null,"time":"2019-12-31 08:21:40"} * 这个为Object不再为String,若为String的话,当数据量非常多的时候,会产生很多转义字符,浪费网络流量,所以这里修改为object类型,其余的工作交给前端。 * 使用方法要求如下: * 1.当是用到第三方的接口时的返回时,比如淘宝的API接口,返回值必须与文档上一致。那么需要传入字符串,淘宝的举例:return ResponseUtil.okWithData(rsp.getBody()); * 虽然这样会产生很多的转义字符,但是没有办法,必须与文档的返回一致,这时data要传入String类型。 * 2.当是我们自己调用我们自己的接口时,就没有必须传入String了,直接传入Object就可以了。举例:查询数据库中的记录,直接返回mybatis的mapper查询的结果list对象就可以,举例: * Mapper.java里 -- List<JdpTbTrade> selectListByTids(String tids); Controller里 -- return ResponseUtil.okWithData(jdpTbTradeMapper.selectListByTids(tids)); * 这样就减少了转义字符,前端调试看着也方便。 */ private Object data;
问题1:这样返回的json
{"flag":true,"code":0,"msg":"ok","data":{"userName":"李昱鑫","userPwd":"123","userAge":100},"tkexp":false,"hurl":null,"time":"2019-12-31 08:19:25"}
其它地方如何使用;
//{"flag":true,"code":0,"msg":"ok","data":{"userName":"李某","userPwd":"123","userAge":100},"tkexp":false,"hurl":null,"time":"2019-12-31 08:19:25"} String json = "{"flag":true,"code":0,"msg":"ok","data":{"userName":"李某","userPwd":"123","userAge":100},"tkexp":false,"hurl":null,"time":"2019-12-31 08:19:25"}"; //1.转成ResponseUtil ResponseUtil responseUtil = objectMapper.readValue(json, ResponseUtil.class); //使用方法1.取出data,由于是一个object对象,把这个对象转成string,然后再转成map进行使用 Map<String, Object> map = objectMapper.readValue(objectMapper.writeValueAsString(responseUtil.getData()), Map.class); System.out.println(map.get("userName")); //使用方法2:取出data转换成String,然后再转成实体类 UserBase userBase = objectMapper.readValue(objectMapper.writeValueAsString(responseUtil.getData()), UserBase.class); System.out.println(userBase.getUserName()); //使用方法3:利用objectMapper直接转换成Map,显然这种方法更简洁,使用这种 Map<String, Object> map2 = objectMapper.convertValue(responseUtil.getData(), Map.class); System.out.println(map2.get("userName")); //使用方法4:利用objectMapper直接转换成实体类,显然这种方法更简洁,使用这种,【推荐使用这种方式】 UserBase userBase2 = objectMapper.convertValue(responseUtil.getData(), UserBase.class); System.out.println(userBase2.getUserName()); return String.valueOf(map.get("userName"));