json 作为配置文件
来源:互联网 发布:linux修改snmp团体名 编辑:程序博客网 时间:2024/05/21 19:32
从以前的 xml 到现在的 properties ,配置方式都很 suck 。我今天发现,既然有 gson 这样的利用反射的 json parser ,何不用 json 呢?
下面是 Config 类,用来保存配置:(使用了 commons-io 2.1 、gson 2.1)
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class Config {
String listen_port;
String hdfs;
private static Config _instance;
static {
Gson gson = new Gson();
FileInputStream configIn = null;
try {
configIn = new FileInputStream("hdfs.conf.json");
_instance = gson.fromJson(IOUtils.toString(configIn), Config.class);
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(configIn);
}
}
public static Config getInstance() {
return _instance;
}
}
下面是配置文件 hdfs.conf.json :
{
listen_port: "8080",
hdfs: "hdfs://192.168.3.233:54310"
}
Gson 在解析 json 的时候使用了反射,所以写出来的代码很简洁。要添加更多的配置属性,只需在类定义里面添加 field ,然后对应的 json 添加相应的项目就行了,其他代码不需要做任何改动。
下面是 Config 类,用来保存配置:(使用了 commons-io 2.1 、gson 2.1)
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class Config {
String listen_port;
String hdfs;
private static Config _instance;
static {
Gson gson = new Gson();
FileInputStream configIn = null;
try {
configIn = new FileInputStream("hdfs.conf.json");
_instance = gson.fromJson(IOUtils.toString(configIn), Config.class);
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(configIn);
}
}
public static Config getInstance() {
return _instance;
}
}
下面是配置文件 hdfs.conf.json :
{
listen_port: "8080",
hdfs: "hdfs://192.168.3.233:54310"
}
Gson 在解析 json 的时候使用了反射,所以写出来的代码很简洁。要添加更多的配置属性,只需在类定义里面添加 field ,然后对应的 json 添加相应的项目就行了,其他代码不需要做任何改动。
0 0
- json 作为配置文件
- json作为配置文件
- Java Web:JSON 作为配置文件,简单读写的方法
- json作为通信报文
- java xml作为配置文件,读取
- Lua 作为配置文件(2)
- struts2注解json 配置文件json
- JS用JSON作为参数
- JS用JSON作为参数
- JSON作为函数的参数
- json配置文件注释
- JSON格式配置文件
- 解析配置文件config.json
- Unity读取 JSon配置文件
- cocoJS配置文件:project.json
- js读json配置文件
- compsoer config.json配置文件
- Unity读取 JSon配置文件
- linux 使用命名管道
- 嵌入式Qt开发环境搭建及移植到开发板----Qt学习笔记
- 发布测试IPA-02
- NYOJ 844 A+B Problem(V)
- linux 使用匿名管道
- json 作为配置文件
- 让static方法具有泛型能力
- 设计模式之策略模式的C++实现
- leetcode 78: Subsets
- cordova
- 走格子问题的动态规划求解
- 2015年8月5日 随笔日记(该文为原创学习笔记有错误请多指教,谢谢)
- 使用string与vector时的一些注意事项
- Java线程(3)Timer和TimerTask