java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot Jackson用法

Springboot中Jackson用法详解

作者:考虑考虑

Springboot自带默认json解析Jackson,可以在不引入其他json解析包情况下,解析json字段,下面我们就来聊聊Springboot中Jackson的用法吧

前言

Springboot自带默认json解析Jackson,可以在不引入其他json解析包情况下,解析json字段

Jackson用法

本文使用的是jdk23Springboot3.4.x版本,如果是在非Springboot项目,就动态添加包

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.18.2</version>
</dependency>

将对象解析为json字符串

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;

    private String name;

    public static void main(String[] args) {
        User user = new User(1L, "aa");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(user);
            System.out.println(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

输出结果为

将json解析为对象

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;

    private String name;

    public static void main(String[] args) {
        User user = new User(1L, "aa");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(user);
            System.out.println(json);
            User user1 = objectMapper.readValue(json, User.class);
            System.out.println(user1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

将json文件转换为json

user.json放置于resources文件夹下

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;

    private String name;

    public static void main(String[] args) {
        User user = new User(1L, "aa");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(user);
            System.out.println(json);
            File file = new File(Objects.requireNonNull(User.class.getClassLoader().getResource("user.json")).getFile());

            User user1 = objectMapper.readValue(file, User.class);
            System.out.println(user1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

输出结果为

将url转换成json

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.net.URI;
import java.net.URL;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;

    private String name;

    public static void main(String[] args) {
        User user = new User(1L, "aa");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(user);
            System.out.println(json);
            URL url = URI.create("http://192.168.69.183:16023/user.json").toURL();

            User user2 = objectMapper.readValue(url, User.class);
            System.out.println(user2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

备注: 搭建个nginx服务器环境,将user.json放入静态资源映射下

jdk20版本以下的URL需要这么写

URL url = new URL("http://192.168.69.183:16023/user.json");

这种jdk20以上过期了,转换成

URL url = URI.create("http://192.168.69.183:16023/user.json").toURL();

字节转换成json

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;

    private String name;

    public static void main(String[] args) {

        ObjectMapper objectMapper= new ObjectMapper();
       String json = """
               {"id":1,"name":"aa"}
               """;
        try {

            User user2 = objectMapper.readValue(json.getBytes(StandardCharsets.UTF_8), User.class);
            System.out.println(user2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

输出结果为

jdk17版本以下字符串需要这些写

String json = "{\"id\":1,\"name\":\"aa\"}";

字符串转义

json数组转对象数组

package cn.com.ut.cloud.demoobjectmapepr.model;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.List;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;

    private String name;

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();
        List<User> userList = List.of(new User(1L, "aa"),
                new User(2L, "bb"));
        try {
            String json = objectMapper.writeValueAsString(userList);
            System.out.println(json);
            List<User> list = objectMapper.readValue(json, new TypeReference<>() {
            });
            System.out.println(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

输出结果为

image.png

json转Map

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Map;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;

    private String name;

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();
        User user = new User(1L, "aa");
        try {
            String json = objectMapper.writeValueAsString(user);
            System.out.println(json);
            Map<String, Object> map = objectMapper.readValue(json,
                    new TypeReference<>() {
                    });
            System.out.println(map);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

输出结果为

JsonNode使用

JsonNode可以将json中的字段取出来

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;

    private String name;

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();
        User user = new User(1L, "aa");
        try {
            String json = objectMapper.writeValueAsString(user);
            System.out.println(json);
            JsonNode jsonNode = objectMapper.readTree(json);

            System.out.println(jsonNode.get("id").asText());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

输出结果为

String id = jsonNode.get("id").asText(); 
double id = jsonNode.get("id").asDouble();
int id = jsonNode.get("id").asInt(); 
long id = jsonNode.get("id").asLong();

动态添加json字段

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;

    private String name;

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();

        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("id", "1");
        objectNode.put("name", "1");
        objectNode.put("age", "1");
        System.out.println(objectNode.toString());
    }
}

输出结果为

总结

可以使用Springboot自身携带的Jackson包操作json,当然,现在还有很多优秀的json解析包,根据自身擅长的做技术选型

以上就是Springboot中Jackson用法详解的详细内容,更多关于Springboot Jackson用法的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文