java 读取json文件方法以及操作json对象方法。

 1   获取本地js文件路径

Fileuri = ParseTools.class.getClassLoader().getResource("com/zxcl/parsejs/XinZhongChengParse.js").toURI();

2  通过路径打开本地json文件

File file = new File(Fileuri);

3 使用读取流读取文件

 reader = new BufferedReader(new FileReader(file));

4 一次读入一行,直到为空为止

      while ((tempString = reader.readLine()) != null) {
                    // 显示行号
                    res += tempString;
                }

所有代码,读取本地json文件

  public static String getGTjsonData() {
        Logger logger = Logger.getLogger(ParseTools.class);
        URI Fileuri;
        net.sf.json.JSONObject ZHLHjson;
        String res = "";
        try {
            Fileuri = ParseTools.class.getClassLoader().getResource("com/zxcl/parsejs/XinZhongChengParse.js").toURI();
            File file = new File(Fileuri);
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                String tempString = null;
                int line = 1;
                // 一次读入一行,直到读入null为文件结束
                while ((tempString = reader.readLine()) != null) {
                    // 显示行号
                    res += tempString;
                }
                reader.close();
            } catch (IOException e) {
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }

        } catch (Exception e) {

        }
        return res;
    }

匹配json对象键,获取相应对象

    // 通过键属性,和匹配键找的对应的对象
    public static JSONObject getJsonValueByKey(JSONArray array, String keyWord, String key) {
        JSONObject reObj = null;
        JSONObject item = null;
        for (int i = 0; i < array.size(); i++) {
            item = array.getJSONObject(i);
            if (item.containsKey(keyWord) && item.get(keyWord).equals(key)) {
                reObj = item;
                break;
            }
        }
        return reObj;
    }
    // 通过键属性,值属性 和匹配键找的对应的对象
    public static String getJsonValStrByKey(JSONArray array, String keyWord, String valWord, String key) {
        String reStr = "";
        JSONObject obj = getJsonValueByKey(array, keyWord, key);
        if (obj != null && obj.get(valWord) != null) {
            reStr = String.valueOf(obj.get(valWord));
        }
        return reStr;
    }
    // 通过键属性,值属性 和匹配键找的对应的对象
    public static BigDecimal getJsonValDecimalByKey(JSONArray array, String keyWord, String valWord, String key) {

        BigDecimal reStr = null;
        String val = getJsonValStrByKey(array, keyWord, valWord, key);
        if (val.equals("")) {
            reStr = new BigDecimal("0.00");
        } else {
            reStr = new BigDecimal(val);
        }
        return reStr;
    }

猜你喜欢

转载自blog.csdn.net/qq_25744257/article/details/84425625