jackson objectMapper json字符串、对象bean、map、数组list互相转换常用的方法 您所在的位置:网站首页 json字符串转换为map jackson objectMapper json字符串、对象bean、map、数组list互相转换常用的方法

jackson objectMapper json字符串、对象bean、map、数组list互相转换常用的方法

2023-08-25 10:37| 来源: 网络整理| 查看: 265

- 对象转json字符串

User user=new User(); String userJson=mapper.writeValueAsString(user);

- Map转json字符串

Map map=new HashMap(); String json=mapper.writeValueAsString(map);

- 数组list转json字符串

Student[] stuArr = {student1, student2}; String jsonfromArr = mapper.writeValueAsString(stuArr);

- json字符串转对象

String expected = "{\"name\":\"Test\"}"; User user = mapper.readValue(expected, User.class);

- json字符串转Map

String expected = "{\"name\":\"Test\"}"; Map userMap = mapper.readValue(expected, Map.class);

- json字符串转对象数组List

String expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]"; CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, User.class); List userList = mapper.readValue(expected, listType);

- json字符串转Map数组List

String expected="[{\"a\":12},{\"b\":23},{\"name\":\"Ryan\"}]"; CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Map.class); List userMapList = mapper.readValue(expected, listType);

- jackson默认将对象转换为LinkedHashMap

String expected = "[{\"name\":\"Ryan\"},{\"name\":\"Test\"},{\"name\":\"Leslie\"}]"; ArrayList arrayList = mapper.readValue(expected, ArrayList.class);

- json字符串与list或map互转的方法

ObjectMapper objectMapper = new ObjectMapper(); //遇到date按照这种格式转换 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); objectMapper.setDateFormat(fmt); String preference = "{name:'张三'}"; //json字符串转map Map preferenceMap = new HashMap(); preferenceMap = objectMapper.readValue(preference, preferenceMap.getClass()); //map转json字符串 String result=objectMapper.writeValueAsString(preferenceMap);

- bean转换为map

List returnList=new ArrayList(); List menuList=menuDAOImpl.findByParentId(parentId); ObjectMapper mapper = new ObjectMapper(); returnList=mapper.convertValue(menuList,new TypeReference(){});


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有