使用GSON在Android Studio中从文件读取JSON。

huangapple go评论147阅读模式
英文:

Reading JSON from file using GSON in Android Studio

问题

  1. fis = openFileInput(filename);
  2. BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
  3. StringBuilder data = new StringBuilder();
  4. String line = null;
  5. line = reader.readLine();
  6. while (line != null)
  7. {
  8. data.append(line).append("\n");
  9. }
  10. data.toString();
  11. reader.close();
  12. fis.close();
  13. Type walletListType = new TypeToken<ArrayList<WalletClass>>(){}.getType();
  14. walletList.add(new Gson().fromJson(data.toString(), 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):

  1. [
  2. {"balance":258,"walletName":"wallet 1"},
  3. {"balance":5222,"walletName":"wallet 2"},
  4. {"balance":1,"walletName":"wallet 3"}
  5. ]

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.

英文:

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:

  1. fis = openFileInput(filename);
  2. BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
  3. StringBuilder data = new StringBuilder();
  4. String line = null;
  5. line = reader.readLine();
  6. while (line != null)
  7. {
  8. data.append(line).append(&quot;\n&quot;);
  9. }
  10. data.toString();
  11. reader.close();
  12. fis.close();
  13. Type walletListType = new TypeToken&lt;ArrayList&lt;WalletClass&gt;&gt;(){}.getType();
  14. 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):

  1. [
  2. {&quot;balance&quot;:258,&quot;walletName&quot;:&quot;wallet 1&quot;},
  3. {&quot;balance&quot;:5222,&quot;walletName&quot;:&quot;wallet 2&quot;},
  4. {&quot;balance&quot;:1,&quot;walletName&quot;:&quot;wallet 3&quot;}
  5. ]

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.

答案1

得分: 1

以下是翻译好的部分:

the Gson提供了许多fromJson方法的重载,以下是它们的签名:

使用GSON在Android Studio中从文件读取JSON。

但是正如你所见,它们中没有任何一个将StringBuilder作为第一个参数。这就是编译器所抱怨的内容。相反,你有一些以String作为第一个参数的构造函数。

因此,将这行代码:

  1. walletList.add(new Gson().fromJson(data, walletListType));

替换为:

  1. walletList.add(new Gson().fromJson(data.toString(), walletListType));

这样你应该就可以继续了。

英文:

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

使用GSON在Android Studio中从文件读取JSON。

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:

  1. walletList.add(new Gson().fromJson(data, walletListType));

with:

  1. walletList.add(new Gson().fromJson(data.toString(), walletListType));

And you should be good to go.

答案2

得分: 0

  1. 你可以使用GSON的类型适配器(Type adapter)来读写文件
  2. 我已经用Kotlin写了这部分代码希望能对你有所帮助
  3. ```kotlin
  4. val builder = GsonBuilder()
  5. builder.registerTypeAdapter(YourData::class.java, MyTypeAdapter())
  6. return builder.create()

示例类型适配器(Type Adapter)

  1. class MyTypeAdapter : TypeAdapter<YourData>() {
  2. @Throws(IOException::class)
  3. override fun read(reader: JsonReader): YourData {
  4. var element1
  5. var element2
  6. reader.beginObject()
  7. while (reader.hasNext()) {
  8. when (reader.nextName()) {
  9. "element1" -> latitude = reader.nextDouble()
  10. "element2" -> dropMessage = reader.nextString()
  11. }
  12. }
  13. reader.endObject()
  14. return YourData(element1, element2)
  15. }
  16. @Throws(IOException::class)
  17. override fun write(out: JsonWriter, yourData: YourData) {
  18. out.beginObject()
  19. out.name("element1").value(yourData)
  20. out.name("element2").value(yourData)
  21. out.endObject()
  22. }
  23. }

使用示例(读取和写入)

  1. fun saveData(yourData: YourData) {
  2. val string = gson.toJson(yourData)
  3. try {
  4. val dataStream = dataOutputStream(yourData)
  5. yourStream.write(string.toByteArray())
  6. yourStream.close()
  7. } catch (e: IOException) {
  8. Log.e("FileRepository", "Error")
  9. }
  10. }
  11. fun getData(): List<YourData> {
  12. val data = mutableListOf<YourData>()
  13. try {
  14. val fileList = dataDirectory().list()
  15. fileList.map { convertStreamToString(YourDataInputStream(it)) }.mapTo(data) {
  16. gson.fromJson(it, YourData::class.java)
  17. }
  18. } catch (e: IOException) {
  19. Log.e("FileRepository", "Error")
  20. }
  21. return data
  22. }
  1. <details>
  2. <summary>英文:</summary>
  3. You can use GSON&#39;s Type adapter to read and write files.
  4. I have written this in kotlin, I hope it helps you.

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

  1. 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()

  1. 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()
}
}

  1. Usage (Read &amp; 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>()

  1. try {
  2. val fileList = dataDirectory().list()
  3. fileList.map { convertStreamToString(YourDataInputStream(it)) }.mapTo(data) {
  4. gson.fromJson(it, YourData::class.java)
  5. }
  6. } catch (e: IOException) {
  7. Log.e(&quot;FileRepository&quot;, &quot;Error&quot;)
  8. }
  9. return data

}

  1. </details>

huangapple
  • 本文由 发表于 2020年3月17日 00:47:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/60709964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定