Jackson序列化对象为JSON

wen java案例 1

本文目录导读:

Jackson序列化对象为JSON

  1. 基本使用
  2. 常用注解
  3. 配置ObjectMapper
  4. 复杂对象序列化
  5. 自定义序列化器
  6. 性能优化技巧

我来详细解释Jackson序列化Java对象为JSON的常用方法。

基本使用

Maven依赖

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

基础序列化

import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        // 序列化对象为JSON字符串
        User user = new User("张三", 25, "zhangsan@example.com");
        String json = mapper.writeValueAsString(user);
        System.out.println(json); // {"name":"张三","age":25,"email":"zhangsan@example.com"}
    }
}
class User {
    private String name;
    private int age;
    private String email;
    // 必须有无参构造器和getter/setter
    public User() {}
    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }
    // 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; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

常用注解

import com.fasterxml.jackson.annotation.*;
public class User {
    @JsonProperty("user_name")  // 指定JSON字段名
    private String name;
    @JsonIgnore  // 忽略该字段
    private String password;
    @JsonFormat(pattern = "yyyy-MM-dd")  // 日期格式化
    private Date birthday;
    @JsonInclude(JsonInclude.Include.NON_NULL)  // 值为null时不包含
    private String phone;
    // getter/setter...
}
// 类级别注解
@JsonIgnoreProperties(ignoreUnknown = true)  // 忽略未知属性
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)  // 蛇形命名
public class User {
    // ...
}

配置ObjectMapper

ObjectMapper mapper = new ObjectMapper();
// 日期格式
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 序列化配置
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);  // 格式化输出
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 反序列化配置
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
// 包含null值
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
// 或排除null值
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

复杂对象序列化

// 集合
List<User> users = Arrays.asList(user1, user2);
String json = mapper.writeValueAsString(users);
// Map
Map<String, Object> map = new HashMap<>();
map.put("name", "张三");
map.put("age", 25);
String json = mapper.writeValueAsString(map);
// 嵌套对象
public class Order {
    private String orderId;
    private User user;
    private List<Product> products;
    // getter/setter...
}
// 泛型
List<User> users = mapper.readValue(json, new TypeReference<List<User>>(){});
// 写入文件
mapper.writeValue(new File("user.json"), user);
// 写入OutputStream
mapper.writeValue(System.out, user);
// 写入字节数组
byte[] bytes = mapper.writeValueAsBytes(user);

自定义序列化器

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
// 自定义序列化器
public class CustomDateSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) 
            throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        gen.writeString(sdf.format(date));
    }
}
// 使用
public class User {
    @JsonSerialize(using = CustomDateSerializer.class)
    private Date birthday;
}
// 或者注册到ObjectMapper
SimpleModule module = new SimpleModule();
module.addSerializer(Date.class, new CustomDateSerializer());
mapper.registerModule(module);

性能优化技巧

// 重用ObjectMapper实例(线程安全)
private static final ObjectMapper MAPPER = new ObjectMapper();
// 启用快速模式(不验证)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 使用字节流而不是字符串
byte[] json = mapper.writeValueAsBytes(user);
// 使用JsonGenerator直接写入
JsonGenerator generator = mapper.getFactory().createGenerator(System.out);
generator.writeStartObject();
generator.writeStringField("name", "张三");
generator.writeNumberField("age", 25);
generator.writeEndObject();
generator.close();

Jackson是目前Java中最流行的JSON处理库之一,性能优秀且功能强大,适合各种复杂的序列化需求。

抱歉,评论功能暂时关闭!