Jackson 是当前用的比较广泛的,用来序列化和反序列化 json 的 Java 的开源框架。
Jackson 的核心模块由三部分组成:
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.9.6version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.9.6version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.6version>
dependency>
jackson-databind 依赖 jackson-core 和 jackson-annotations,所以可以只显示地添加jackson-databind依赖,jackson-core 和 jackson-annotations 也随之添加到 Java 项目工程中。
适用场景:Java属性名与需要转换的JSON字符串不一致的场景
java bean:
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestJsonBean {
@JsonProperty(value = "test_name")
private String name;
@JsonProperty(value = "bean_number")
private Integer beanNumber;
@JsonProperty(value = "bean_account")
private Double beanAccount;
}
Test 测试:
package com.jackson.example;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class TestJackson {
@Test
public void test1() {
ObjectMapper objectMapper = new ObjectMapper();
TestJsonBean bean = new TestJsonBean();
bean.setBeanAccount(2.53);
bean.setBeanNumber(15);
bean.setName("测试JSON");
try {
String result = objectMapper.writeValueAsString(bean);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
打印结果:
{"test_name":"测试JSON","bean_number":15,"bean_account":2.53}