JSON-B是用于将Java对象与JSON消息相互转换的标准绑定层。它定义了一种默认的映射算法,用于将现有的Java类转换为JSON。

添加依赖:

<dependencies>
    <!-- JSON-P -->
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>jakarta.json</artifactId>
        <version>1.1.5</version>
        <scope>runtime</scope>
    </dependency>

    <!-- JSON-B API -->
    <dependency>
        <groupId>jakarta.json.bind</groupId>
        <artifactId>jakarta.json.bind-api</artifactId>
        <version>1.0.1</version>
    </dependency>

    <!-- Yasson (JSON-B implementation) -->
    <dependency>
        <groupId>org.eclipse</groupId>
        <artifactId>yasson</artifactId>
        <version>1.0.3</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

序列化和反序列化的使用:

public static class Dog {
    public String name;
    public int age;
    public boolean bites;
}

// Create a dog instance
Dog dog = new Dog();
dog.name = "Falco";
dog.age = 4;
dog.bites = false;

// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);

// Deserialize back
dog = jsonb.fromJson("{\"name\":\"Falco\",\"age\":4,\"bites\":false}", Dog.class);

对集合类型序列化:

// List of dogs
List dogs = new ArrayList();
dogs.add(falco);
dogs.add(cassidy);

// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dogs);

// We can also deserialize back into a raw collection, but since there is no way to infer a type here,
// the result will be a list of java.util.Map instances with string keys.
dogs = jsonb.fromJson(result, ArrayList.getClass());

格式化输出:

// Create custom configuration with formatted output
JsonbConfig config = new JsonbConfig()
    .withFormatting(true);

// Create Jsonb with custom configuration
Jsonb jsonb = JsonbBuilder.create(config);

// Use it!
String result = jsonb.toJson(pojo);

@JsonbProperty用于更改一个特定属性的名称。

public class Person {
    @JsonbProperty("person-name")
    public String name;

    public String profession;
}

生成的JSON文档将如下所示:

{
    "person-name": "Jason Bourne",
    "profession": "Super Agent"
}

@JsonbDateFormat和@JsonbNumberFormat批注来完成:

public class Person {
    private String name;

    @JsonbDateFormat("dd.MM.yyyy")
    private LocalDate birthDate;

    @JsonbNumberFormat("#0.00")
    private BigDecimal salary;

    // public getters/setters ...
}

JSON-B fastjson jackson gson 序列化的组件很多,大家可以根据自己的熟练程度和喜好使用。