java解析json文件

1.文件传输解析

@ResponseBody
@PostMapping(value = "importJson")
public String importJson(@RequestParam(value = "file") MultipartFile file) throws Exception {
    byte[] fileBytes = file.getBytes();
    String fileName = file.getOriginalFilename();
    String jsonString = new String(fileBytes, StandardCharsets.UTF_8.name());
    List<MyBean> list = JSON.parseArray(jsonString,MyBean.class);
    //处理list集合
    return "1";
}

2.本地文件路径解析

2.1.依赖
 <!-- commons -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

 <!-- json解析 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.69</version>
</dependency>
2.2.json路径及示例

resources目录下

在这里插入图片描述

my.json

[
	{
		"id":"1",
		"name":"张三"
	},
	{
		"id":"2",
		"name":"李四"
	}
]
2.2.3.代码实现
public static void main(String[] args) throws IOException {
    //类路径classpath
    ClassPathResource resource = new ClassPathResource("my.json");
    File file = resource.getFile();
    String fileStr = FileUtils.readFileToString(file);
    List<JSONObject> list = JSONObject.parseArray(fileStr, JSONObject.class);
    System.out.println(list);
}

版权声明:本文为qq_42513284原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。