Serializing a Collection of Java Records into a JSON Array 序列化一个 set java 集合为JSON 数组格式
引用自 https://adambien.blog/roller/abien/entry/serializing_a_collection_of_java
A collection (Set) of Java Record instances:
用于存入 set 集合的对象有两个参数一个 是 text ,一个是 uri
public record Link(String text, String uri) {}
使用 JSON-B 转换,如下代码
can be serialized with JSON-B into a JSON array:
import org.junit.jupiter.api.Test;
import java.util.Set;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
public class JSONBTest {
@Test
public void serialize() {
var links = Set.of(new Link("json-b", "http://json-b.net"),
new Link("jakarta ee", "https://jakarta.ee"),
new Link("microprofile", "https://microprofile.io"));
Jsonb jsonb = JsonbBuilder.create();
var jsonArray = jsonb.toJson(links);
System.out.println(jsonArray);
}
}
The code above generates the following output:
[{"text":"jakarta ee","uri":"https://jakarta.ee"},{"text":"microprofile","uri":"https://microprofile.io"},{"text":"json-b","uri":"http://json-b.net"}]
Tested with Apache Johnzon:
使用到的包
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jsonb_1.0_spec</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-json_1.1_spec</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.apache.johnzon</groupId>
<artifactId>johnzon-jsonb</artifactId>
<version>1.2.10</version>
</dependency>
上面这是一个将集合转换程JSON 数组格式的使用指南,使用了三个包,然后用他们的toJson 方法来转换,注意 jdk 版本要高于 8
我自己实现后的代码如下
import org.junit.Test;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import java.util.Set;
/**
* @Author : ivan
* @Date 2021/2/5 11:18
*/
public class JSONBTest {
@Test
public void serialize(){
Set<Link> links = Set.of(new Link("json-b", "http://json-b.net"),
new Link("jakarta ee", "https://jakarta.ee"),
new Link("microprofile", "https://microprofile.io"));
Jsonb jsonb = JsonbBuilder.create();
String s = jsonb.toJson(links);
System.out.println(s);
}
}
坚持做好每件事,然后再做下一件。