将复杂JSON数据转换为HashMap存入Couchbase Lite数据库
Got it, let's break down how to take your existing Retrofit model classes, convert them into a Map<String, Object> (since we’ll need support for nested structures), and persist that into Couchbase Lite. This approach plays perfectly with your complex nested JSON structure.
Step 1: Convert Model Objects to a Map
Since you already have model classes mapped to your JSON via Retrofit, the easiest way to handle conversion is using Gson (which you’re probably already using with Retrofit anyway). It automatically handles all nested objects like forms, variables, and options without extra boilerplate.
Example Code
First, ensure Gson is in your dependencies (add this to your build.gradle if missing):
implementation 'com.google.code.gson:gson:2.10.1'
Then convert your top-level Project model to a map:
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; // Assume your Retrofit model class is named Project Project project = ...; // Your fetched model from Retrofit Gson gson = new Gson(); // Serialize model to JSON, then parse back to a generic map String json = gson.toJson(project); Map<String, Object> projectMap = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
If you prefer manual conversion (for full control over data types), write helper methods in each model class:
// Inside your Project class public Map<String, Object> toMap() { Map<String, Object> map = new HashMap<>(); map.put("project_id", this.projectId); map.put("project_name", this.projectName); List<Map<String, Object>> formMaps = new ArrayList<>(); for (Form form : this.forms) { formMaps.add(form.toMap()); } map.put("forms", formMaps); return map; } // Inside your Form class public Map<String, Object> toMap() { Map<String, Object> map = new HashMap<>(); map.put("form_name", this.formName); map.put("form_id", this.formId); List<Map<String, Object>> variableMaps = new ArrayList<>(); for (Variable variable : this.variables) { variableMaps.add(variable.toMap()); } map.put("variables", variableMaps); return map; } // Inside your Variable class public Map<String, Object> toMap() { Map<String, Object> map = new HashMap<>(); map.put("id", this.id); map.put("variable_name", this.variableName); map.put("variable_label", this.variableLabel); map.put("input_type", this.inputType); map.put("hidden_text", this.hiddenText); // Optional: Convert "required" string to boolean for easier querying map.put("required", "1".equals(this.required)); map.put("options", this.options.toMap()); // Add a toMap() method to your Options model map.put("default_value", this.defaultValue); map.put("max_length", this.maxLength); map.put("min_length", this.minLength); map.put("pre_condition", this.preCondition); map.put("post_condition", this.postCondition); map.put("order_in_form", this.orderInForm); return map; }
Step 2: Insert the Map into Couchbase Lite
Once you have your Map<String, Object>, create a MutableDocument and save it to your Couchbase Lite database.
Example Code
import com.couchbase.lite.Database; import com.couchbase.lite.MutableDocument; import com.couchbase.lite.SaveMode; // Get your initialized Couchbase Lite database instance Database db = ...; // Follow Couchbase's setup docs to initialize this // Use project_id as the document ID for easy future lookups MutableDocument doc = new MutableDocument(project.getProjectId()) .setData(projectMap); // Save the document (REPLACE overwrites if it already exists) try { db.save(doc, SaveMode.REPLACE); System.out.println("Project saved to Couchbase Lite successfully!"); } catch (Exception e) { e.printStackTrace(); }
Key Notes for Your Data
- Nested Structures: Couchbase Lite fully supports nested
MapandListobjects, so yourformsandvariableswill be stored correctly and remain queryable. - Data Type Consistency: Fields like
requiredare strings in your JSON—consider converting them to booleans (as shown in the manual conversion example) to make future queries more intuitive. - Document ID: Using
project_idas the document ID is a smart move because it’s unique and lets you fetch the project directly later withdb.getDocument("PROJ10001").
Quick Query Example for Later
When you need to query nested data (e.g., find all variables with input type "options"), Couchbase Lite’s fluent API handles nested paths easily:
import com.couchbase.lite.Query; import com.couchbase.lite.QueryBuilder; import com.couchbase.lite.SelectResult; import com.couchbase.lite.Expression; Query query = QueryBuilder.select(SelectResult.all()) .from(Expression.database(db)) .where(Expression.property("forms.variables.input_type").equalTo(Expression.string("options"))); // Execute the query and process results as needed
内容的提问来源于stack exchange,提问作者fritz-playmaker

