使用GSON读取和写入数据 [英] read and write data with GSON

查看:161
本文介绍了使用GSON读取和写入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找一个关于如何在我的android应用程序中使用GSON读取和写入数据的好例子。有人可以指给我看一个好例子吗?



我的教授给出了这个例子来写作:

  Vector v = new Vector(10.0f,20.0f); 
Gson gson = new Gson();
String s = gson.toJson(v);

我会如何将其保存到文件中?

> String filename =myfile.txt;

Vector v = new Vector(10.0f,20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);

FileOutputStream outputStream;

尝试{
outputStream = openFileOutput(filename,Context.MODE_PRIVATE);
outputStream.write(s.getBytes());
outputStream.close();
} catch(Exception e){
e.printStackTrace();
}

如何读回:

  FileInputStream fis = context.openFileInput(myfile.txt,Context.MODE_PRIVATE); 
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
字符串行; ((line = bufferedReader.readLine())!= null){
sb.append(line);
while
}

String json = sb.toString();
Gson gson = new Gson();
Vector v = gson.fromJson(json,Vector.class);


I am struggling to find a good example on how to read and write data in my android app using GSON. Could someone please show me or point me to a good example? I am using this for data persistence between activities.

My professor gave this example to for writing:

Vector v = new Vector(10.0f, 20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);

How would I go about saving that to a file?

解决方案

How to save your JSON into a file on internal storage:

String filename = "myfile.txt";

Vector v = new Vector(10.0f, 20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);

FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(s.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

How to read it back:

 FileInputStream fis = context.openFileInput("myfile.txt", Context.MODE_PRIVATE);
 InputStreamReader isr = new InputStreamReader(fis);
 BufferedReader bufferedReader = new BufferedReader(isr);
 StringBuilder sb = new StringBuilder();
 String line;
 while ((line = bufferedReader.readLine()) != null) {
     sb.append(line);
 }

 String json = sb.toString();
 Gson gson = new Gson();
 Vector v = gson.fromJson(json, Vector.class);

这篇关于使用GSON读取和写入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆