附上java解析json文件内容的工具类
1.工具类
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
/**
* @ClassName CommonUtil
* @Description TODO
* @Author lifay
* @Date 2020/2/18 10:21
**/
public class CommonUtil {
private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);
/**
* 读取json文件返回数据
* @throws IOException
*/
public static Object readJsonData(String filePath,Class clazz){
String jsonString = null;
Reader reader = null;
try{
ClassPathResource resource = new ClassPathResource(filePath);
if (!resource.exists()) {
logger.warn("{}文件不存在!",filePath);
return null;
}
File file = resource.getFile();
reader = new InputStreamReader(new FileInputStream(file),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
jsonString = sb.toString();
} catch (IOException e){
logger.warn("{}文件内容解析失败!",filePath);
return null;
}
return JSONObject.parseObject(jsonString,clazz);
}
}
2.调用
List users = (List) CommonUtil.readJsonData("/json/user.json", List.class);
3.json文件(json文件放在resources目录下,结构为/src/main/resources/json/user.json)
[{"id":"1","name":"user1","age":"18"},{"id":"2","name":"user2","age":"28"}]