Java读取Json文件方法

JSON格式

Json是一种轻量级数据交换格式,一般可以用来表示一个对象或者一个数组。
对象,是组无序的键值对,键值之间用“:”连接,键值用双引号("")括起来,键值对间用",“相连。最外层扩上大括号”{}"

{
“count”: 10,
“time_interval”: 10,
“url”: “https://blog.csdn.net/kiba_zwei/article/details/103645213”
}

数组,是一组对象,对象间用“,”连接

{
“config”: [
{
“count”: 10,
“time_interval”: 10,
“url”: “https://blog.csdn.net/kiba_zwei/article/details/103645213”
},
{
“count”: 10,
“time_interval”: 10,
“url”: “https://blog.csdn.net/kiba_zwei/article/details/104176295”
}
]
}

Java读取本地Json文件

Json解析有专门的JSONObject包一共是6个,需要逐一下载。阿里也推出了一个Fastjson的包更加快捷,推荐使用这个。资源

读取Json

为了方便阅读所以一般Json文件都是写成换行的形式,但是在解析Json时,需要将其归为一个无换行的字符串,所以需要我们将逐行读入并且拼接成一个字符串。

public static String parseConfig() {
    String fileName = CONFIG_V2;
    File jsonFile = new File(fileName);
    try (Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8")) {
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        return sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

解析Json

JSON提供了解析Json的接口parseObject(String)直接调用就好了,

JSONObject jobj = JSON.parseObject(configs);

对解析的结果可以直接利用键值对来取值了,包中提供了getInteger,getString,getJSONArray等接口,可以根据需要进行使用。

// 对象
int count = jsonObject.getInteger("count");
// 数组
JSONArray configList = jobj.getJSONArray("config");
JSONObject jsonObject = configList.getJSONObject(i);
发布了20 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/kiba_zwei/article/details/104336492
今日推荐