使用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"
}    
比较简单的JSONBuilder:(.net 2.0, jdk1.5) - 只有两个文件:JSONBuilder(.cs,.java) , JSONBuilderDelegates(.cs,.java) - 不用考虑对象嵌套输出格式的匹配问题 - 自动字符串转义 - 支持常见数据类型、以及常用的数据结构如: 任意数组(Array),IMap,IList,IEmutable等 - 支持任意扩展,通过注册自定义类型的转换方法(参看JSONBuilderTest(.cs,.java) 和 JSONBuilderDelegates(.cs,.java))可支持任意类型的json字符串转换 - 支持自定义的包含 public string toJSON() 的对象的输出(忽略大小写) - 带有测试的VS2005和Eclispe完整项目 - 版权:可任意使用、分发、改良(只要包含原作者信息) // 转换回调函数接口 --> JSONBuilderDelegates.cs public delegate string JSONBuilderDelegates(object value, bool useSingleQuote); 或 --> JSONBuilderDelegates.java public static String JSONBuilderDelegates(Object value, boolean useSingleQuote); //-->JSONBuilderTest.cs (JSONBuilderTest.java) 比如 .net: //demo custom class public class CustomClass { public string name = "Hu Changwei"; public string nickName = "koqiui"; public string email = "koqiui@163.com"; public string gender = "male"; public bool married = true; public DateTime birthDate = new DateTime(1978, 5, 21); } //demo custom json convertor public static string fromCustomClass(object value, bool useSingleQuote) { if (value == null) { return JSONBuilder.NullStr; } if (value.GetType() == typeof(CustomClass)) { CustomClass objValue = value as CustomClass; JSONBuilder jb = new JSONBuilder(useSingleQuote); jb.startObject(); // jb.add("Author", objValue.name); jb.add("nickname", objValue.nickName); jb.add("email", objValue.email); jb.add("married", objValue.married); jb.add("birthdate", objValue.birthDate); // jb.endObject(); return jb.toJSON(); } return JSONBuilder.NullStr; } [Test] public void test_customConvertor() { JSONBuilder.setJSONConvertor(typeof(CustomClass), new ToJSONDelegate(fromCustomClass)); JSONBuilder jb = new JSONBuilder(); jb.addValue(new CustomClass()); Console.WriteLine(jb.toJSON()); }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值