0

I have written the code below to store a complex Java Object containing multiple other objects as a file on the disk

public static void savePattern(ArrayList<Pattern> p,String filename){
    String fn;
    Gson gson = new Gson();
    JsonElement element = gson.toJsonTree(p, new TypeToken<ArrayList<Pattern>>() {}.getType());
    JsonArray jsonArray = element.getAsJsonArray();
    String json = gson.toJson(jsonArray);
    try {
        //write converted json data to a file named "file.json"
        if(filename != null){
            fn = "JsonObjects/objects.json";
        }
        else{
            fn = "JsonObjects/" + filename + ".json";
        }
        FileWriter writer = new FileWriter("fn");
        writer.write(json);
        writer.close();
    } 
    catch (IOException e) {
        e.printStackTrace();
    }
}

I get completely stuck when i'm trying to write the method to load the file from disk into an ArrayList that has the type.

public static ArrayList<Pattern> loadPattern(){
    ArrayList<Pattern> patterns = new ArrayList<>();
    Gson gson = new Gson();
    JsonParser jsonParser = new JsonParser();
    try {
        BufferedReader br = new BufferedReader(new FileReader("JsonObjects/objects.json"));
        JsonObject jo = (JsonObject)jsonParser.parse(br);

    } catch (IOException e) {
        e.printStackTrace();
    }
    return patterns;        
}

1 Answer 1

1

Have you tried:

public static List<Pattern> loadPattern(){
    ArrayList<Pattern> patterns = new ArrayList<>();
    Gson gson = new Gson();
    JsonParser jsonParser = new JsonParser();
    try {
        BufferedReader br = new BufferedReader(new FileReader("JsonObjects/objects.json"));
        JsonElement jsonElement = jsonParser.parse(br);

        //Create generic type
        Type type = new TypeToken<List<Pattern>>() {}.getType();
        return gson.fromJson(jsonElement, type);

    } catch (IOException e) {
        e.printStackTrace();
    }
    return patterns;        
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.