我有一个数据库,我想将数据从表导出到android中的json文件
我的表有column1,column2和column3 我的json应该是
tablename: [
row 1:[
column1:{"data1"},
column2:{"data2"},
column3:{"data3"}
],
row 2:[
column1:{"data1"},
column2:{"data2"},
column3:{"data3"}
]
]
如何实现?
答案 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