在我的一门编程课程中,我的任务是创建一个用于读取 json 并将其写入文件的类。
我使用了 json.simple 库,但很快意识到几乎所有行都收到了“类型安全警告”?
然后我尝试尽可能多地使用 ArrayList 和 HashMap,因为 JSONObject 和 JSONArray 扩展器这些。据我了解,这是一个问题。
我对编程很陌生,非常感谢您提供一些提示,以及我如何解决任务的提示。
如何摆脱这些类型的安全警告?
我的代码:
`
//imports
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Collection;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
public class ReadAndWrite {
/**
* This is a class for reading and writing to the userData file stored in the users home directory.
* The file is stored in json format. The classes are first converted to json format and then written to the file.
* The classes are then read from the file and converted back to the classes.
*/
/**
* For the first version of the application we will only have one user.
* This is why we have a dummy name for the user. To parse the classes to json
* we are using the json-simple library. JSONObjects
*/
private static String dummyName = "dummyName";
private static String fileLocation = System.getProperty("user.home") + System.getProperty("file.separator") + "loftUserData.json";
private JSONParser parser = new JSONParser();
private Collection<User> userClasses = new ArrayList<User>();
private Collection<Workout> workoutsClasses = new ArrayList<Workout>();
private Collection<Exercise> exercisesClasses = new ArrayList<Exercise>();
private Collection<Set> setsClasses = new ArrayList<Set>();
/**
* Private method for setting up a set class to json format.
* @param list of sets
* @return ArrayList<HashMap<String, Object>> -> sets in json format
*/
private ArrayList<HashMap<String, Object>> setSetsJsonArray(List<Set> list) {
ArrayList<HashMap<String, Object>> setsArray = new ArrayList<HashMap<String, Object>>();
int i = 0;
for (Set set : list) {
HashMap<String, Object> setJson = new HashMap<String, Object>();
setJson.put("setNumber", ++i);
setJson.put("weight", set.getWeight());
setJson.put("reps", set.getReps());
setsArray.add(setJson);
}
return setsArray;
}
/**
* Private method for setting up a exercise class to json format.
* @param list of exercises
* @return ArrayList<HashMap<String, Object>> -> exercises in json format
*/
private ArrayList<HashMap<String, Object>> setExercisesJsonArray(List<Exercise> list) {
ArrayList<HashMap<String, Object>> exercisesArray = new ArrayList<HashMap<String, Object>>();
for (Exercise exercise : list) {
HashMap<String, Object> exerciseJson = new HashMap<String, Object>();
exerciseJson.put("exerciseName", exercise.getName());
exerciseJson.put("sets", setSetsJsonArray(exercise.getSets()));
exercisesArray.add(exerciseJson);
}
return exercisesArray;
}
/**
* Private method for setting up a workout class to json format.
* @param workout
* @return HashMap<String, Object> -> workout in json format
*/
private HashMap<String, Object> formatWorkoutClassToJson(Workout workout) {
HashMap<String, Object> workoutJson = new HashMap<String, Object>();
workoutJson.put("exercises", setExercisesJsonArray(workout.getExercises()));
workoutJson.put("date", workout.getDate().toString());
return workoutJson;
}
//Writing a workout class to the userData file in json format
/**
* The method to be used for writing a workout class to the userData file in json format.
* @param workout
*/
public void writeWorkoutToUser(Workout workout) {
ArrayList<HashMap<String, Object>> existingData = readDataFromFile();
ArrayList<HashMap<String, Object>> users = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> user = new HashMap<String,Object>();
// Setting up user
if (existingData == null) {
user.put("name", dummyName);
user.put("workouts", new ArrayList<HashMap<String, Object>>());
} else {
HashMap<String, Object> userDummy = existingData.get(0);
user = userDummy;
}
// Adding to user
HashMap<String, Object> workoutInJSONFormat = this.formatWorkoutClassToJson(workout);
ArrayList<HashMap<String, Object>> workoutsJsonArray = (ArrayList<HashMap<String, Object>>) user.get("workouts");
workoutsJsonArray.add(workoutInJSONFormat);
users.add(user);
JSONArray jsonFormat = new JSONArray();
jsonFormat.addAll(users);
try (FileWriter file = new FileWriter(fileLocation)) {
file.write(jsonFormat.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Private method for reconstructing the user class from a JSONArray format.
* @param users JSONArray of users
* @return ArrayList of users, in our case there is only one user.
*/
private ArrayList<User> classReconstructor(JSONArray users) {
for (Object userObject : users) {
JSONObject user = (JSONObject) userObject;
String name = (String) user.get("name");
JSONArray workouts = (JSONArray) user.get("workouts");
for (Object workoutObject : workouts) {
JSONObject workout = (JSONObject) workoutObject;
LocalDate date = LocalDate.parse((String) workout.get("date"));
JSONArray exercises = (JSONArray) workout.get("exercises");
for (Object exerciseObject : exercises) {
JSONObject exercise = (JSONObject) exerciseObject;
String exerciseName = (String) exercise.get("exerciseName");
JSONArray sets = (JSONArray) exercise.get("sets");
for (Object setObject : sets) {
JSONObject set = (JSONObject) setObject;
int weight = ((Long) set.get("weight")).intValue();
int reps = ((Long) set.get("reps")).intValue();
Set newSet = new Set(weight, reps);
setsClasses.add(newSet);
}
Exercise newExercise = new Exercise(exerciseName);
for (Set set : setsClasses) {
newExercise.addSet(set);
}
exercisesClasses.add(newExercise);
}
Workout newWorkout = new Workout(date);
for (Exercise exercise : exercisesClasses) {
newWorkout.addExercise(exercise);
}
workoutsClasses.add(newWorkout);
}
User newUser = new User(name);
for (Workout workout : workoutsClasses) {
newUser.addWorkout(workout);
}
userClasses.add(newUser);
}
return (ArrayList<User>) userClasses;
}
/**
* Private method for reading data from the file.
* @return JSONArray of all users. In our case there is only one user.
*/
private ArrayList<HashMap<String, Object>> readDataFromFile() {
try (FileReader reader = new FileReader(fileLocation)){
if (reader.ready()) {
Object obj = parser.parse(reader);
JSONArray users = (JSONArray) obj;
ArrayList<HashMap<String, Object>> usersList = (ArrayList<HashMap<String, Object>>) users;
return usersList;
} else {
//The file can be empty this is not an error, it just means that there is no data to read.
}
} catch (FileNotFoundException e) {
// If it is not found, it will be created at a later point, so this is fine
return null;
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
return null;
}
/**
* The method to be used for getting the user class from the file.
* @return User class
*/
public User returnUserClassFromFile() {
ArrayList<HashMap<String, Object>> users = readDataFromFile();
if (users == null) {
return new User(dummyName);
}
JSONArray usersJson = (JSONArray) users;
ArrayList<User> user = this.classReconstructor(usersJson);
User userClass = user.get(0);
return userClass;
}
问题出现的地方:
ArrayList<HashMap<String, Object>> workoutsJsonArray = (ArrayList<HashMap<String, Object>>) user.get("workouts");
jsonFormat.addAll(users);
ArrayList<HashMap<String, Object>> usersList = (ArrayList<HashMap<String, Object>>) users;
我尝试使用 ArrayList 和 HashMap 代替 JSONArray 和 JSONObject
您遇到的类型安全警告是因为您正在使用HashMap<String, Object>集合并尝试将它们转换为更具体的类型。虽然可以完成此转换,但它不是类型安全的,因为集合的泛型类型未明确定义,从而导致未经检查的类型转换。
要摆脱这些类型安全警告,您应该考虑使用允许您直接使用 Java 对象的 JSON 库,例如 Google 的Gson或Jackson。这些库将允许您将 JSON 数据直接映射到 Java 类并避免转换问题。
以下是使用 Gson 库重构代码的方法:
通过此重构,您不再需要在 JSON 集合和 Java 对象之间进行转换,从而使您的代码更安全且更易于维护。