java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Jackson处理JSON

使用Jackson进行JSON生成与解析的新手指南

作者:五行星辰

这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

1. 核心依赖

Spring Boot 默认集成 Jackson,无需额外依赖:

<!-- 如果使用 Spring Boot Starter Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 基础用法

2.1 对象转 JSON(序列化)

ObjectMapper mapper = new ObjectMapper();
User user = new User("张三", 25);
String json = mapper.writeValueAsString(user);
// 输出:{"name":"张三","age":25}

2.2 JSON 转对象(反序列化)

String json = "{\"name\":\"李四\",\"age\":30}";
User user = mapper.readValue(json, User.class);

3. 常用注解

3.1 字段控制

public class User {
    @JsonProperty("user_name")  // 自定义JSON字段名
    private String name;

    @JsonIgnore  // 忽略字段
    private String password;

    @JsonInclude(JsonInclude.Include.NON_NULL)  // 非空时序列化
    private String email;
}

3.2 时间格式

public class Order {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime createTime;
}

3.3 多态处理

@JsonTypeInfo(use = Id.NAME, property = "type")
@JsonSubTypes({
    @Type(value = Cat.class, name = "cat"),
    @Type(value = Dog.class, name = "dog")
})
public abstract class Animal {}

4. 自定义配置(Spring Boot)

4.1 全局配置

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper()
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)  // 日期不转时间戳
            .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
}

4.2 配置项示例

# application.yml
spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    default-property-inclusion: non_null
    deserialization:
      FAIL_ON_UNKNOWN_PROPERTIES: false  # 忽略未知字段

5. 高级技巧

5.1 处理泛型

TypeReference<ResultDTO<List<User>>> typeRef = new TypeReference<>() {};
ResultDTO<List<User>> result = mapper.readValue(json, typeRef);

5.2 流式 API(处理大文件)

JsonFactory factory = mapper.getFactory();
try (JsonParser parser = factory.createParser(new File("large.json"))) {
    while (parser.nextToken() != null) {
        // 逐条处理
    }
}

5.3 自定义序列化器

public class MoneySerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider provider) {
        gen.writeString(value.setScale(2, RoundingMode.HALF_UP) + "元");
    }
}

// 使用注解
public class Product {
    @JsonSerialize(using = MoneySerializer.class)
    private BigDecimal price;
}

6. 常见问题解决

6.1 循环引用问题

// 方法1:使用 @JsonIgnore 打断循环
public class Order {
    @JsonIgnore
    private User user;
}

// 方法2:配置全局忽略
mapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);

6.2 枚举处理

public enum Status {
    @JsonValue  // 序列化时使用 code
    OK(1), ERROR(2);

    private final int code;
    // 反序列化时根据 code 转换
    @JsonCreator
    public static Status fromCode(int code) { /* ... */ }
}

6.3 处理特殊字符

mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
// 输入:{"name":"张三"} → 输出:{"name":"\u5F20\u4E09"}

7. 性能优化

7.1 启用缓存

mapper.enable(MapperFeature.USE_ANNOTATIONS);
mapper.enable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);

7.2 线程安全配置

ObjectMapper mapper = new ObjectMapper();
// 配置为线程安全
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

7.3 使用第三方模块

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());

8. 安全注意事项

8.1 防止 XXE 攻击

mapper.configure(JsonParser.Feature.ALLOW_EXTERNAL_PROCESSING, false);

8.2 反序列化防护

// 启用类型检查
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// 或使用注解 @JsonTypeInfo

最佳实践总结

通过以上方法,可以高效安全地处理 JSON 数据。

到此这篇关于使用Jackson进行JSON生成与解析的新手指南的文章就介绍到这了,更多相关Jackson处理JSON内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

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