0

I have a parser method to parse a json file. I created it for ClassA, but I want to use it for different Classes such as ClassB and ClassC also

My code:

public static List<ClassA> parseFromFile(String path){
    JSONParser parser = new JSONParser();
    List<ClassA> list = new ArrayList<>(Collections.emptyList());

    try {
        BufferedReader in = new BufferedReader(new FileReader(path));

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            JSONArray a = (JSONArray) parser.parse(inputLine);

            for (Object o : a) {
                JSONObject jsonObject = (JSONObject) o;

                ClassA a = new Gson().fromJson(String.valueOf(jsonObject), ClassA.class);
                list.add(a);
            }
        }
        in.close();
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }

    return list;
}
Emma Alden
  • 129
  • 16
  • 1
    Use generics `public static List parseFromFile(String path, Class targetclass){` and this `T a = new Gson().fromJson(String.valueOf(jsonObject), targetclass);` – CodeScale Apr 11 '20 at 16:00

1 Answers1

1

Pass the class in as a parameter. You need to change these lines:

public static <T> List<T> parseFromFile(String path, Class<T> type){
    JSONParser parser = new JSONParser();
    List<T> list = new ArrayList<>(Collections.emptyList());

and this line:

                T a = new Gson().fromJson(String.valueOf(jsonObject), klass);

If I were you would review if this implementation makes sense: it looks like you are parsing the file contents first with the org.json library, then converting back into JSON, and parsing again using Gson. You only need to parse once:

    BufferedReader in = new BufferedReader(new FileReader(path));
    T a = new Gson().fromJson(in, klass);
Joni
  • 108,737
  • 14
  • 143
  • 193
  • Thanks for your answer. But i want to ask that my file contains many objects so "T a = new Gson().fromJson(in, klass);" does not work. Can you help me with that? – Emma Alden Apr 11 '20 at 17:18
  • How does your file contain many objects? Do you mean the file contains a JSON array? Or just several objects one after the other with nothing separating them? – Joni Apr 11 '20 at 17:20
  • Yes It contains JSON array. Sorry for misleading. – Emma Alden Apr 11 '20 at 17:22
  • Are the objects in the array all the same type? – Joni Apr 11 '20 at 17:23
  • 1
    Then you'd use a "type token" instead of Class - see full question and answers here https://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type – Joni Apr 11 '20 at 17:44