将数据从数据库迁移到json文件android

时间:2020-08-18 14:50:03

标签: android json android-database

我有一个数据库,我想将数据从表导出到android中的json文件

我的表有column1,column2和column3 我的json应该是

tablename: [
   row 1:[
      column1:{"data1"},
      column2:{"data2"},
      column3:{"data3"}
      ],
 row 2:[
      column1:{"data1"},
      column2:{"data2"},
      column3:{"data3"}
      ]
]

如何实现?

1 个答案:

答案 0 :(得分:0)

您可以使用Gson对Java对象进行序列化/反序列化:https://github.com/google/gson

示例:

Gson gson = new Gson();
String json = gson.toJson(MY_LIST);
FileOutputStream outputStream;
outputStream = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
outputStream.write(json.getBytes());
outputStream.close();

MY_LIST是一个列表,其中填充了表中的数据。可序列化类的示例:

public class MyClass implements Serializable {
    String field;
    List<MySecondClass> secondList = new ArrayList<>();
    
    static class MySecondClass implements Serializable{
        int id;
        String data;
    }
}

如果您使用的是Kotlin,则可以使用https://github.com/Kotlin/kotlinx.serialization