jackson 如何将实体转json json字符串转实体

 更新时间:2021年10月19日 10:20:59   作者:介寒食  
这篇文章主要介绍了jackson 实现将实体转json json字符串转实体,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

将实体转json json字符串转实体

@Autowired
ObjectMapper objectMapper;

实体转json

  String data = "";  //一个json串
  Student stu = new Student ();
 stu = objectMapper.readValue(data, Student .class);// json字符串转实体
public <T> String writeAsString(T t) throws JsonProcessingException {
    return objectMapper.writeValueAsString(t);
} 
String aa = writeAsString(stu);

json转实体

    public <T> T readValue(String data) {
        try {
            return objectMapper.readValue(data, new TypeReference<T>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

使用Jackson操作json数据,各场景实例

该篇内容,结合实例介绍使用jackson来操作json数据:

在pom.xml文件中添加 ,Jackson 依赖:

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.1</version>
        </dependency>
 
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.11.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.11.1</version>
        </dependency>

示例中使用到的实体类, UserEntity.java

/**
 * @Author : JCccc
 * @CreateTime : 2020/3/18
 * @Description :
 **/
public class UserEntity {
    private Integer id;
    private String name;
    private Integer age;
 
  // set get 方法 和 toString 等方法就不粘贴出来了
}

在介绍示例前,先看一张图,使用jackson如:

1. 对象(示例为 UserEntity)转 json 数据

writeValueAsString 方法

    public static void main(String[] args) throws JsonProcessingException {
        UserEntity userEntity=new UserEntity();
        userEntity.setId(100);
        userEntity.setName("JCccc");
        userEntity.setAge(18);
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writerWithDefaultPrettyPrinter()
                .writeValueAsString(userEntity);
        System.out.println(jsonString);
    }

控制台输出:

格式很漂亮,是因为使用了 :

咱们不需要漂亮,所以后面的我都不使用格式的方法了,转换的时候,只需要 writeValueAsString 就够了 。

2. json 数据 转 对象

readValue 方法

        ObjectMapper mapper = new ObjectMapper();
        //json字符串转对象
        UserEntity userEntityNew = mapper.readValue(jsonString, UserEntity.class);
        System.out.println(userEntityNew);

控制台输出:

3. map 转 json 数据

        ObjectMapper mapper = new ObjectMapper();
        Map map=new HashMap();
        map.put("A",1);
        map.put("B",2);
        map.put("C",3);
        map.put("D",4);
        String jsonMap = mapper.writeValueAsString(map);
        System.out.println(jsonMap);

控制台输出:

4. json 数据 转 map

        ObjectMapper mapper = new ObjectMapper();
        //json字符串转为Map对象
        Map mapNew=mapper.readValue(jsonMap, Map.class);
        System.out.println(mapNew);

控制台输出:

5. List<UserEntity> 转 json 数据

        ObjectMapper mapper = new ObjectMapper();
        UserEntity userEntity1=new UserEntity();
        userEntity1.setId(101);
        userEntity1.setName("JCccc1");
        userEntity1.setAge(18);
        UserEntity userEntity2=new UserEntity();
        userEntity2.setId(102);
        userEntity2.setName("JCccc2");
        userEntity2.setAge(18);
        UserEntity userEntity3=new UserEntity();
        userEntity3.setId(103);
        userEntity3.setName("JCccc3");
        userEntity3.setAge(18);
        List<UserEntity> userList=new ArrayList<>();
        userList.add(userEntity1);
        userList.add(userEntity2);
        userList.add(userEntity3);
        
        String jsonList = mapper.writeValueAsString(userList);
        System.out.println(jsonList);

控制台输出:

6. json 数据 转 List<UserEntity>

        ObjectMapper mapper = new ObjectMapper();
        List<UserEntity> userListNew= mapper.readValue(jsonList,new TypeReference<List<UserEntity>>(){});
        System.out.println(userListNew.toString());

控制台输出:

7.接口接收稍微复杂一点的json数据,如何拆解

现在模拟了一串稍微复杂一些的json数据,如:

{
	"msg": "success",
	"data": [
		{
			"id": 101,
			"name": "JCccc1",
			"age": 18
		},
		{
			"id": 102,
			"name": "JCccc2",
			"age": 18
		},
		{
			"id": 103,
			"name": "JCccc3",
			"age": 18
		}
	],
	"status": 200
}

那么我们接口接收时,如果操作呢?

1.直接使用 @RequestBody Map map 接收,里面如果嵌套list,那就拿出对应的value转list,然后该怎么拿怎么拿。

    @PostMapping("testJackson")
    public void testJackson(@RequestBody Map map) {
 
        System.out.println(map);
        String  msg = String.valueOf(map.get("msg"));
        System.out.println(msg);
        List dataList = (List) map.get("data");
        System.out.println(dataList.toString());
    }

2.使用字符串接收json数据 @RequestBody String jsonStr , 那么就使用jackson把这个json数据转为Map,然后该怎么拿怎么拿。

    @PostMapping("testJackson")
    public void testJackson(@RequestBody String jsonStr) throws JsonProcessingException {
 
        System.out.println(jsonStr);
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(jsonStr, Map.class);
        String  msg = String.valueOf(map.get("msg"));
        System.out.println(msg);
        String  status = String.valueOf(map.get("status"));
        System.out.println(status);
        List dataList = (List) map.get("data");
        System.out.println(dataList.toString());
    }

好的,该篇就到此。

ps: 为啥我要科普这个jackson的使用么?这个算是基本的操作了,原本我经手的很多项目都用到的fastjson ,其实使用起来也杠杠的。

除了jackson是springboot web包的内部解析框架外,其实还有一些原因。

懂的人自然会明白。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • IDEA自定义Maven archetype的方法步骤

    IDEA自定义Maven archetype的方法步骤

    在创建Maven的项目时我们发现了一个很不方便的问题,就是每次创建Maven的工程的时候,都需要选择一个骨架,本文主要介绍了IDEA自定义Maven archetype的方法步骤,感兴趣的可以了解一下
    2022-03-03
  • idea中的lombok不生效的四种解决方法

    idea中的lombok不生效的四种解决方法

    Lombok项目是一个java库,它可以自动插入到编辑器和构建工具中,本文将详细给大家介绍idea中的lombok不生效的四种解决方法,需要的朋友可以参考下
    2023-05-05
  • 基于OpenID Connect及Token Relay实现Spring Cloud Gateway

    基于OpenID Connect及Token Relay实现Spring Cloud Gateway

    这篇文章主要介绍了基于OpenID Connect及Token Relay实现Spring Cloud Gateway,Spring Cloud Gateway旨在提供一种简单而有效的方式来路由到API,并为API提供跨领域的关注点,如:安全性、监控/指标和弹性
    2022-06-06
  • 简单实现Java版学生管理系统

    简单实现Java版学生管理系统

    这篇文章主要为大家详细介绍了简单实现Java版学生管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-06-06
  • Java Char的简单工具类CharUtil分享

    Java Char的简单工具类CharUtil分享

    下面小编就为大家分享一篇Java Char的简单工具类CharUtil,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • mybatis-plugin插件执行原理解析

    mybatis-plugin插件执行原理解析

    这篇文章主要介绍了mybatis-plugin插件执行原理,我们就需要来研究下Executor,ParameterHandler,ResultSetHandler,StatementHandler这4个对象的具体跟sql相关的方法,然后再进行修改,就可以直接起到aop的作用,需要的朋友可以参考下
    2022-10-10
  • JAVA遍历map的几种实现方法代码

    JAVA遍历map的几种实现方法代码

    这篇文章主要介绍了JAVA遍历map的几种实现方法,有需要的朋友可以参考一下
    2014-01-01
  • SpringBoot整合mybatis结合pageHelper插件实现分页

    SpringBoot整合mybatis结合pageHelper插件实现分页

    在本篇文章里小编给大家整理的是关于SpringBoot整合mybatis使用pageHelper插件进行分页操作相关知识点,需要的朋友们学习下。
    2020-02-02
  • springboot+mybatis配置控制台打印sql日志的方法

    springboot+mybatis配置控制台打印sql日志的方法

    这篇文章主要介绍了springboot+mybatis配置控制台打印sql日志的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-08-08
  • intellij idea中spring boot properties文件不能自动提示问题解决

    intellij idea中spring boot properties文件不能自动提示问题解决

    这篇文章主要介绍了intellij idea中spring boot properties文件不能自动提示问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02

最新评论