如何在SQLite数据库中存储JSON对象

Kev*_*vik 55 database sqlite android json

如何在SQLite数据库中存储JSON对象?什么是正确的方法?

一个地方是blob类型列.如果我可以将JSON对象转换为字节数组并使用Fileoutputstream

另一个想法是将文本列存储为String

import org.json.JSONObject;

JSONObject jsonObject;

public void createJSONObject(Fields fields) {
    jsonObject = new JSONObject();

    try {
        jsonObject.put("storedValue1", fields.storedValue1);
        jsonObject.put("storedValue2", fields.storedValue2);
        jsonObject.put("storedValue3", fields.storedValue3);
        jsonObject.put("storedValue4", fields.storedValue4);
        jsonObject.put("storedValue5", fields.storedValue5);
        jsonObject.put("storedValue6", fields.storedValue6);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

Pan*_*mar 75

将JSONObject转换为String并保存为TEXT/VARCHAR.检索同一列时,将String转换为JSONObject.

例如

写入DB

String stringToBeInserted = jsonObject.toString();
//and insert this string into DB
Run Code Online (Sandbox Code Playgroud)

从DB读取

String json = Read_column_value_logic_here
JSONObject jsonObject = new JSONObject(json);
Run Code Online (Sandbox Code Playgroud)

  • 您是否意识到这样插入会带来任何性能问题? (2认同)
  • @JohnAndrews当然.等待你的宝贵回应.但更好的存储图像的方法是使用blob.阅读http://stackoverflow.com/questions/9357668/how-to-store-image-in-sqlite-database. (2认同)
  • SQLite具有新的JSON扩展。参见oisin的评论。 (2认同)
  • 如果您费心阅读文档,就会发现没有 SQLite json 数据类型。只是函数的集合。 (2认同)

Ois*_*sin 28

另一种方法是使用SQLite的新JSON扩展.我自己只是遇到过这个问题:https://www.sqlite.org/json1.html这将允许您执行一定级别的查询存储的JSON.如果您使用VARCHAR或TEXT存储JSON字符串,则无法查询它.这是一篇很棒的文章,展示了它的用法(在python中)http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/

  • 从您链接的第一页开始:“json1 扩展(当前)将 JSON 存储为普通文本。向后兼容性约束意味着 SQLite 只能存储 NULL、整数、浮点数、文本和 BLOB 值。它是无法添加第六种“JSON”类型。” 所以,是的,即使您想使用 JSON 扩展功能,您也应该将 JSON 存储在 TEXT 列中。 (10认同)

Pra*_*eep 5

没有数据类型。您只需将其存储为 VARCHAR 或 TEXT 即可。jsonObject.toString();