Jackson使用(jackson 怎么用)

Jackson使用(jackson 怎么用)

编码文章call10242025-07-11 21:50:124A+A-

在 Java 中使用 Jackson 进行 字符串转对象对象转字符串 是非常常见的操作,主要通过 ObjectMapper 类来实现。

一、添加依赖(Maven)

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.16.1</version> <!-- 使用最新稳定版本 -->
</dependency>

二、定义一个 POJO 示例类

package org.example.json;

public class User {
    private String name;
    private int age;

    // 必须有无参构造函数
    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter 和 Setter 方法
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

三、Jackson 核心用法

1. 对象转 JSON 字符串

package org.example.json;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        User user = new User("Alice", 30);

        // 对象转 JSON 字符串
        String jsonStr = mapper.writeValueAsString(user);
        System.out.println(jsonStr); // {"name":"Alice","age":30}
    }
}

2. JSON 字符串转对象

String json = "{\"name\":\"Bob\",\"age\":25}";

// JSON 字符串转为对象
User newUser = mapper.readValue(json, User.class);
System.out.println(newUser.getName()); // Bob

四、处理复杂结构(泛型、集合等)

1. JSON 转 List

String jsonArray = "[{\"name\":\"Alice\",\"age\":30},{\"name\":\"Bob\",\"age\":25}]";

List<User> users = mapper.readValue(jsonArray, new TypeReference<List<User>>() {});
users.forEach(u -> System.out.println(u.getName()));

2. JSON 转 Map<String, Object>

String jsonMap = "{\"name\":\"Alice\",\"age\":30}";

Map<String, Object> map = mapper.readValue(jsonMap, new TypeReference<Map<String, Object>>() {});
System.out.println(map.get("name")); // Alice

五、美化输出格式(Pretty Print)

String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
System.out.println(prettyJson);

六、忽略空字段或 null 值

// 忽略 null 值字段
ObjectMapper newMapper = new ObjectMapper();
newMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

User nullUser = new User();
nullUser.setName(null);
nullUser.setAge(0);

String nullStr = newMapper.writeValueAsString(nullUser);
System.out.println(nullStr); // {"age":0}

七、自定义字段名(注解方式)

User user = new User();
user.setName("Tom");

String json = mapper.writeValueAsString(user);
System.out.println(json); // {"age":0,"full_name":"Tom"}

八、完整示例代码汇总

package org.example.json;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

public class JacksonExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 创建对象
        User user = new User("Alice", 30);

        // 对象转 JSON
        String jsonStr = mapper.writeValueAsString(user);
        System.out.println("对象转 JSON: " + jsonStr);

        // JSON 转对象
        String inputJson = "{\"name\":\"Bob\",\"age\":25}";
        User parsedUser = mapper.readValue(inputJson, User.class);
        System.out.println("JSON 转对象: " + parsedUser.getName());

        // JSON 数组转 List
        String jsonArray = "[{\"name\":\"Alice\",\"age\":30},{\"name\":\"Bob\",\"age\":25}]";
        List<User> userList = mapper.readValue(jsonArray, new TypeReference<List<User>>() {
        });
        System.out.println("JSON 转 List: " + userList.size());

        // JSON 转 Map
        String jsonMap = "{\"name\":\"Charlie\",\"age\":40}";
        Map<String, Object> map = mapper.readValue(jsonMap, new TypeReference<Map<String, Object>>() {
        });
        System.out.println("JSON 转 Map: " + map.get("name"));
    }

    static class User {
//        @JsonProperty("full_name")
        private String name;
        private int age;

        public User() {
        }

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}


总结

操作

方法

对象 → JSON 字符串

writeValueAsString(obj)

JSON 字符串 → 对象

readValue(json, Class<T>)

JSON 数组 → List

readValue(json, new TypeReference<List<T>>() {})

JSON → Map

readValue(json, new TypeReference<Map<String, T>>() {})

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4