Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

Using the Gson library, how do I convert a JSON string to an ArrayList of a custom class JsonLog? Basically, JsonLog is an interface implemented by different kinds of logs made by my Android app--SMS logs, call logs, data logs--and this ArrayList is a collection of all of them. I keep getting an error in line 6.

public static void log(File destination, JsonLog log) {

    Collection<JsonLog> logs = null;

    if (destination.exists()) {

        Gson gson = new Gson();

        BufferedReader br = new BufferedReader(new FileReader(destination));

        logs = gson.fromJson(br, ArrayList<JsonLog>.class); // line 6

        // logs.add(log);

        // serialize "logs" again

    }

}

It seems the compiler doesn't understand I'm referring to a typed ArrayList. What do I do?

1 Answer

0 votes
by (46k points)

You may use TypeToken to load the json string into a custom object.

logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());

Related questions

0 votes
1 answer
asked Oct 17, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...