JSON-B随Java EE 8一起提供,并且已经包含在API中:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
在独立的应用程序中,例如CLI,您将必须添加SPI(服务提供商实现)依赖项:
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.4</version>
</dependency>
默认情况下,公共POJO字段是序列化的,私有字段序列化需要自定义。
以下POJO:
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;
public class Configuration {
public String workshop;
public int attendees;
private final static String CONFIGURATION_FILE = "airhacks-config.json";
public Configuration save() {
Jsonb jsonb = JsonbBuilder.create(new JsonbConfig().withFormatting(true));
try (FileWriter writer = new FileWriter(CONFIGURATION_FILE)) {
jsonb.toJson(this, writer);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
return this;
}
public static Configuration load() {
if (!Files.exists(Paths.get(CONFIGURATION_FILE))) {
return new Configuration().save();
}
try (FileReader reader = new FileReader(CONFIGURATION_FILE)) {
return JsonbBuilder.create().fromJson(reader, Configuration.class);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
}
...直接写成:
@Test
public void loadAndSave() {
Configuration configuration = Configuration.load();
configuration.attendees = 13;
configuration.workshop = "Cloudy Jakarta EE";
configuration.save();
}
至:
{
"attendees": 13,
"workshop": "Cloudy Jakarta EE"
}