SpringBoot解析json文件

tech2025-12-12  1

SpringBoot解析json文件

## 第一步:要有一个自定义的json文件 例如: 文件名:user.json [ { "username":"张三", "userage":"20" }, { "username":"莉莉", "userage":"18" } ] ## 第二步:要有一个实体类 例如: @Data 等同于getter setter public class User implements Serializable { private String username; private String userage; } ## 第三步:json变为实体类---的工具类 例如: import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.springframework.util.ResourceUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class JsonUser { private JsonUser(){} private static JsonUser JsonUser; public static JsonUser getInstance() { if (JsonUser == null) { JsonUser = new JsonUser(); } return JsonUser; } public List<User> readJson() throws Exception { List<User> list= new ArrayList<>(); // 读取 json 文件 File file = ResourceUtils.getFile("classpath:static/user.json"); // System.out.println(file); String jsonData = jsonRead(file); //System.out.println(jsonData); JSONArray array = JSONArray.parseArray(jsonData); // System.out.println(array); for (int i = 0; i < array.size(); i++) { JSONObject jsonObject2 = array.getJSONObject(i); // System.out.println(jsonObject2); String username = jsonObject2.getString("username"); String userage = jsonObject2.getString("userage"); // 把 读取到 jsonObject2 弄成一个个的对象 User user = new User(); user.setUsername(username); user.setUserage(userage); System.out.println(User); list.add(user); // 把对象 放到了集合中.. } return list; } private String jsonRead(File file) { FileInputStream is = null; StringBuilder stringBuilder = null; try { /** * 文件有内容才去读文件 */ is = new FileInputStream(file); InputStreamReader streamReader = new InputStreamReader(is,"utf-8"); BufferedReader reader = new BufferedReader(streamReader); String line; stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { // stringBuilder.append(line); stringBuilder.append(line); } reader.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } return String.valueOf(stringBuilder); } } ## 第四步:如何调用 例如: List<User> list=JsonUser.getInstance().readJson();
最新回复(0)