I'm trying to read JSON from an internal storage file into a list of objects.
My code for reading the file and GSON
is:
fis = openFileInput(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
StringBuilder data = new StringBuilder();
String line = null;
line = reader.readLine();
while (line != null)
{
data.append(line).append("\n");
}
data.toString();
reader.close();
fis.close();
Type walletListType = new TypeToken<ArrayList<WalletClass>>(){}.getType();
walletList.add(new Gson().fromJson(data, walletListType));
However, I'm getting the error
Cannot resolve method fromJson('java.lang.stringBuilder, java.lang.reflect.Type')
The JSON I'm trying to load is (it's inside the square brackets because I've serialized it from a list of objects):
[
{"balance":258,"walletName":"wallet 1"},
{"balance":5222,"walletName":"wallet 2"},
{"balance":1,"walletName":"wallet 3"}
]
I know a common fix for this is changing the import code from org
to com
, however I've already made sure it is com
.
the Gson provide a lot of overloads for the fromJson
method, here are their signatures:
But as you can see none of them takes the StringBuilder as first argument. That is what the compiler is complaining about. Instead you have constructors that take a String as first argument.
So replace this line:
walletList.add(new Gson().fromJson(data, walletListType));
with:
walletList.add(new Gson().fromJson(data.toString(), walletListType));
And you should be good to go.