1

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.

3
  • replace line = reader.readLine(); inside while loop Commented Mar 16, 2020 at 16:54
  • @Kirguduck That part works fine. But putting the reader inside the while loop doesn't change anything about the GSON error Commented Mar 16, 2020 at 17:00
  • if you use line = reader.readLine(); out of loop then you will read only first line of your json. add logs and check - what do you read. Now you read only part of json and as it appears this is cause of error Commented Mar 16, 2020 at 17:08

2 Answers 2

1

the Gson provide a lot of overloads for the fromJson method, here are their signatures:

fromJson overloads

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah I tried that and it didn't work. I already have: data.toString();
What error message do you get when you use data.toString()? Obviously not the same, right?
My mistake, it did solve it. I assumed that having data.toString() outside of the fromJson method it would still work however it doesn't for some reason. Cheers
0

You can use GSON's Type adapter to read and write files. I have written this in kotlin, I hope it helps you.

val builder = GsonBuilder()
      builder.registerTypeAdapter(YourData::class.java, MyTypeAdapter())
      return builder.create()

Sample Type Adapter

class MyTypeAdapter : TypeAdapter<YourData>() {

  @Throws(IOException::class)
  override fun read(reader: JsonReader): YourData {
    var element1
    var element2
    reader.beginObject()
    while (reader.hasNext()) {
      when (reader.nextName()) {
        "element1" -> latitude = reader.nextDouble()
        "element2" -> dropMessage = reader.nextString()
      }
    }
    reader.endObject()

    return YourData(element1, element2)
  }

  @Throws(IOException::class)
  override fun write(out: JsonWriter, yourData: YourData) {
    out.beginObject()
    out.name("element1").value(yourData)
    out.name("element2").value(yourData)
    out.endObject()
  }
}

Usage (Read & Write)

fun saveData(yourData: YourData) {
    val string = gson.toJson(yourData)
    try {
      val dataStream = dataOutputStream(yourData)
      yourStream.write(string.toByteArray())
      yourStream.close()
    } catch (e: IOException) {
      Log.e("FileRepository", "Error")
    }
  }

fun getData(): List<YourData> {
    val data = mutableListOf<YourData>()

    try {
      val fileList = dataDirectory().list()

      fileList.map { convertStreamToString(YourDataInputStream(it)) }.mapTo(data) {
        gson.fromJson(it, YourData::class.java)
      }
    } catch (e: IOException) {
      Log.e("FileRepository", "Error")
    }

    return data
  }

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.