Java读取本地json文件

Maven依赖

Fastjson

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.75</version>
</dependency>

commons-io

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.11.0</version>
</dependency>

Json文件内容

{
"name":"网站",
"num":3,
"sites":[ "Google", "Runoob", "Taobao" ]
}

代码示例

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;

public class Test {

    public static void main(String[] args) throws Exception {
        //类路径资源
        ClassPathResource classPathResource = new ClassPathResource("test.json");
        //获取file对象
        File file = classPathResource.getFile();
        //将file对象转为字符串
        String s = FileUtils.readFileToString(file);
        //将字符串解析为JSONObject对象
        JSONObject jsonObject = JSONObject.parseObject(s);
        //获取数组对象
        JSONArray sites = jsonObject.getJSONArray("sites");
        //遍历数组对象
        sites.forEach(x -> {
            System.out.println(x.toString());
        });
        //将json转为对象
        t t = JSONObject.parseObject(s, t.class);
        System.out.println(t);
    }

}
@Data
class t{
    String name;
    Integer age;
    String[] sites;
}

运行效果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容