有没有办法将领域数据库导出到CSV/JSON



我想将我的领域数据库导出到Android中的CSV/JSON。领域数据库中是否有一些可以做到这一点的内构建方法?

有一种将领域转换为CSV链接的iOS方法。我想要Android中的类似方法。

我通过电子邮件得到了领域支持的答复。

不幸的是,我们还没有此功能。您可以在此处看到它:https://github.com/realm/realm-java/issues/2880

您可以使用动态API并自己编写脚本来执行类似的功能。

我能够将以下解决方案拼凑在一起:

// Grab all data from the DB in question (TaskDB):
RealmResults<TaskDB> resultsDB = realm.where(TaskDB.class).findAll();
// Here we need to put in header fields
String dataP = null;
String header = DataExport.grabHeader(realm, "TaskDB");
// We write the header to file
savBak(header);
// Now we write all the data corresponding to the fields grabbed above:
for (TaskDB taskitems: resultsDB) {
    dataP = taskitems.toString();
    // We process the data obtained and add commas and formatting:
    dataP = dataProcess(dataP);
    // Workaround to remove the last comma from final string
    int total = dataP.length() - 1;
    dataP =  dataP.substring(0,total);
    // We write the data to file
    savBak(dataP);
}

我将尽我所能解释它在做什么,并包括所有相应的代码(全部参考第一个代码块(。

我做的第一个是使用我在单独的类(dataexport.grabheader(中写的以下方法抓住标头。它需要2个参数:所讨论的领域对象和DB对象模型名称:

public static String grabHeader(Realm realm, String model){
    final RealmSchema schema = realm.getSchema();
    final RealmObjectSchema testSchema = schema.get(model);
    final String header = testSchema.getFieldNames().toString();
    String dataProcessed = new String();
    Pattern p = Pattern.compile("\[(.*?)\]");
    Matcher m = p.matcher(header);
    while(m.find()) {
        dataProcessed += m.group(1).trim().replaceAll("\p{Z}","");
    }
    return dataProcessed;

在grabheader中,我应用了一些正则魔术,并吐出一个字符串,该字符串将用作标头,并具有适当的逗号(字符串dataprocorsessed(。在这种情况下,在获得所需的数据后,我使用了另一种方法(Savbak(将信息写入文件,该信息获取1个字符串参数:

    @Override
    public void savBak(String data){
        FileOutputStream fos = null;
        try {
            fos = openFileOutput(FILE_NAME, MODE_PRIVATE | MODE_APPEND);
            fos.write(data.getBytes());
            fos.write("n".getBytes());
            Log.d("tester", "saved to: " + getFilesDir() + "/" + FILE_NAME);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

" savbak"方法将信息写入变量中指定的file_name,我们具有标题信息。编写标题后,我们使用forloop进行基本上与DB进行相同的过程,但是在处理线路后,我还必须包括2行才能删除尾随逗号。每行都附加到文件和中提琴,CSV格式化的良好。

从这里开始,您可以使用其他现有的方法将CSV转换为JSON以及其他任何方法,并通过JSON将信息放回领域。当涉及到更高级的元素(例如主要键等(时,我不确定,但它适合我的特定项目需求。

请原谅任何"不好的代码"练习,因为我是Java/Android的新手