JSON文件读取

JSON格式的配置文件(config.json):
 {
     version : "1.1.0",
     db_config : {
         url: "jdbc:mysql://192.168.1.118/xxx?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull",
         username : "root",
         password : "root123"
     },
     redis : {
         host : "192.168.1.1",
         port : "6379",
         timeout : "1000",
         password : "123456789"
     }
     
 }

 

测试Demo

package common.util;

public class JSONFileReaderTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("version :  " + JSONFileReader.load("version"));// version : 1.1.0
        System.out.println("db_config.url : " + JSONFileReader.load("db_config.url")); //db_config.url : jdbc:mysql://19...
    }

}

JSONFileReader .java 主要使用了fastjson.jar,具体可参考http://code.alibabatech.com/wiki/display/FastJSON/Home
 1 package common.util;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 import org.apache.commons.io.FileUtils;
 7 
 8 import com.alibaba.fastjson.JSON;
 9 import com.alibaba.fastjson.JSONObject;
10 
11 public class JSONFileReader {
12     private static JSONObject jsonObject;
13 
14     static  {
15         String fileName = JSONFileReader.class.getResource("/").getPath() +"config/config.json";
16         try {
17             String json = FileUtils.readFileToString(new File(fileName));
18             jsonObject = JSON.parseObject(json);
19         } catch (IOException e) {
20             e.printStackTrace();
21         }
22     }
23     
24     public static final String load(String key) {
25         String[] keyArr = key.split("\\.");
26         JSONObject targetObject = jsonObject;
27         int length = keyArr.length - 1;
28         try {
29             for (int i = 0; i < length; i++) {
30                 targetObject = targetObject.getJSONObject(keyArr[i]);
31             }
32             return targetObject.getString(keyArr[length]);
33         } catch (Exception e) {
34             e.printStackTrace();
35         }
36         return "";
37     }
38 }

posted @ 2013-05-03 14:54  易木  阅读(587)  评论(0编辑  收藏  举报