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

2023-09-05 05:58:12 作者:水晶~沫兮

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

一处是BLOB类型列。如果我可以转换的JSON对象转换成字节数组,使用的FileOutputStream

另一个想法是在一个文本列存储为一个字符串

 进口org.json.JSONObject;

的JSONObject的JSONObject;

公共无效createJSONObject(字段的字段){
    的JSONObject =新的JSONObject();

    尝试 {
        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);
    }赶上(JSONException E){
        e.printStackTrace();
    }
}
 

解决方案

的JSONObject转换成字符串,并保存为文本/ VARCHAR。当检索同一列的字符串转换成JSONObject的。的

例如

写入到数据库的

 字符串stringToBeInserted = jsonObject.toString();
//并插入这个字符串到数据库
 
如何创建sqlite数据库

从数据库读取的

  JSON字符串= Read_column_value_logic_here
的JSONObject的JSONObject =新的JSONObject(JSON);
 

how do I store a JSON Object in an SQLite database? What is the correct way?

one place is the blob type column. if i can convert the JSON object into byte array and use Fileoutputstream

the other idea is to store in a text column as a 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();
    }
}

解决方案

Convert JSONObject into String and save as TEXT/ VARCHAR. While retrieving the same column convert the String into JSONObject.

For example

Write into DB

String stringToBeInserted = jsonObject.toString();
//and insert this string into DB

Read from DB

String json = Read_column_value_logic_here
JSONObject jsonObject = new JSONObject(json);