1. 程式人生 > 其它 >使用JSON-B讀寫配置檔案

使用JSON-B讀寫配置檔案

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"
}