FastJson
public static void main(String[] args) {
MjUserDTO mjUserDTO = new MjUserDTO();
mjUserDTO.setId(Long.valueOf(120621));
mjUserDTO.setUserId(Long.valueOf(120621));
mjUserDTO.setNickName("qingshan");
Integer bizId=2;
Integer bizType=3;
Map<String,String> map=new HashMap<>();
map.put("bizId",String.valueOf(bizId));
map.put("bizType",String.valueOf(bizType));
map.put("mjUserDTO",JSON.toJSONString(mjUserDTO));
String str = JSON.toJSONString(map);
Map<String,String> parse = (Map)JSON.parse(str);
String mjUserDTO1 = parse.get("mjUserDTO");
MjUserDTO data = JSON.parseObject(mjUserDTO1,MjUserDTO.class);
System.out.println(data.getNickName());
//获取json字符串中深度层级的数据
String jsonResult="{\n" +
" \"rspCode\": \"000000\",\n" +
" \"rspMsg\": \"操作完成\",\n" +
" \"debuggerErrorMsg\": null,\n" +
" \"resultData\": {\n" +
" \"token\": \"86988ae9-077c-4a3f-807d-39840403efc3\"\n" +
" }\n" +
"}";
JSONObject result = JSONObject.parseObject(jsonResult);
JSONObject resultDataJson=result.getJSONObject("resultData");
//如果还有更深层的再继续解析
String token = resultDataJson.getString("token");
}
Jackson
@Test
void test1() throws JsonProcessingException {
//对象转jsonstr
StudentInfoDTO studentInfoDTO=new StudentInfoDTO();
studentInfoDTO.setName("石银博");
studentInfoDTO.setSex("男");
studentInfoDTO.setAge(23);
studentInfoDTO.setBeiZhu("备注");
ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(studentInfoDTO);
System.out.println(result);
}
@Test
void test2() throws JsonProcessingException {
//jsonstr转对象
String jsonStr="{\"name\":\"石银博\",\"sex\":\"男\",\"age\":23,\"beiZhu\":\"备注\"}";
ObjectMapper mapper = new ObjectMapper();
StudentInfoDTO studentInfoDTO = mapper.readValue(jsonStr, StudentInfoDTO.class);
System.out.println(studentInfoDTO);
}
@Test
void test3() throws JsonProcessingException {
//jsonstr转map
String jsonStr="{\"name\":\"石银博\",\"sex\":\"男\",\"age\":23,\"beiZhu\":\"备注\"}";
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map= mapper.readValue(jsonStr, new TypeReference<Map<String,Object>>(){});
System.out.println(map);
}