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

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

 

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

2. json 数据 转 对象

3. map 转 json 数据

4. json 数据 转 map

5. List<UserEntity> 转 json 数据

6. json 数据 转 List<UserEntity>

7.接口接收稍微复杂一点的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包的内部解析框架外,其实还有一些原因。

 

懂的人自然会明白。

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: 在Spring Boot中,可以使用Jackson库将JSON转换为数组。具体步骤如下: 1. 在pom.xml文件中添加Jackson依赖: ``` <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.3</version> </dependency> ``` 2. 创建一个Java类来表示JSON数组的结构,例如: ``` public class MyArray { private List<String> items; public List<String> getItems() { return items; } public void setItems(List<String> items) { this.items = items; } } ``` 3. 在Controller中使用@RequestBody注解将JSON转换Java对象: ``` @PostMapping("/myarray") public void myArray(@RequestBody MyArray myArray) { List<String> items = myArray.getItems(); // do something with the array } ``` 4. 发送POST请求时,将JSON作为请求体发送: ``` { "items": ["item1", "item2", "item3"] } ``` 这样就可以将JSON转换为数组了。 ### 回答2: 在Spring Boot中将JSON转换为数组,主要是通过使用Jackson库中的ObjectMapper类来实现。 首先,需要在项目的pom.xml文件中添加Jackson库的依赖: ```xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> ``` 接下来,在代码中创建一个ObjectMapper对象,并使用其readValue方法将JSON字符串转换为数组。例如: ```java import com.fasterxml.jackson.databind.ObjectMapper; public class JsonToArrayConverter { public static void main(String[] args) { // JSON字符串 String json = "[1, 2, 3, 4, 5]"; ObjectMapper objectMapper = new ObjectMapper(); try { // 将JSON字符串转换为数组 int[] array = objectMapper.readValue(json, int[].class); // 打印数组元素 for (int i : array) { System.out.println(i); } } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码中,将JSON字符串"[1, 2, 3, 4, 5]"转换为了一个整型数组,并通过循环打印出了数组中的元素。 在实际的Spring Boot应用中,可以将上述代码放在Controller或Service层的方法中,根据具体的业务需求进行调用和处理。 ### 回答3: 在Spring Boot中,可以使用`Jackson`库将JSON转换为数组。 首先,需要在`pom.xml`文件中添加`Jackson`库的依赖: ```xml <dependencies> <!-- 其他依赖... --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> </dependencies> ``` 接下来,假设我们有一个包含JSON数组的字符串`jsonStr`,可以使用以下代码将其转换为数组: ```java import com.fasterxml.jackson.databind.ObjectMapper; public class JsonToArrayExample { public static void main(String[] args) throws Exception { String jsonStr = "[1, 2, 3, 4, 5]"; // 创建ObjectMapper对象 ObjectMapper objectMapper = new ObjectMapper(); // 将JSON转换为数组 int[] array = objectMapper.readValue(jsonStr, int[].class); // 打印数组元素 for (int value : array) { System.out.println(value); } } } ``` 上述代码使用`ObjectMapper`类的`readValue`方法将JSON字符串转换为整型数组。在`readValue`方法中,第一个参数是JSON字符串,第二个参数是目标数组的类型。 运行上述代码,将会输出以下结果: ``` 1 2 3 4 5 ``` 以上就是使用Spring Boot将JSON转换为数组的方法。我们通过添加`Jackson`库的依赖,并使用`ObjectMapper`类的`readValue`方法,将JSON字符串转换为目标数组。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小目标青年

对你有帮助的话,谢谢你的打赏。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值