JFeurich
JFeurich

Reputation: 3

How to Parse a JAVA ArrayList from a JSON file

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;        
}

Upvotes: 0

Views: 3645

Answers (1)

David Limkys
David Limkys

Reputation: 5133

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;        
}

Upvotes: 1

Related Questions