Created
February 24, 2018 00:23
-
-
Save HodGreeley/da7b2b60a8f5de901c2e0f327d0914ac to your computer and use it in GitHub Desktop.
Storing Objects in a JSONArray with Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.couchbase.mobile; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.util.Log; | |
import com.couchbase.lite.Database; | |
import com.couchbase.lite.DatabaseConfiguration; | |
import com.couchbase.lite.MutableDocument; | |
import com.fasterxml.jackson.core.type.TypeReference; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import java.util.Map; | |
public class MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
try { | |
String json = "[ { \"id\": \"1\" }, { \"id\": \"2\" }, { \"id\": \"3\" } ]"; | |
ObjectMapper mapper = new ObjectMapper(); | |
DatabaseConfiguration options = new DatabaseConfiguration(this); | |
Database database = new Database("example", options); | |
int cnt = 0; | |
Map<String, Object>[] maps = mapper.readValue(json, new TypeReference<Map<String, Object>[]>() {}); | |
for (Map<String, Object> map: maps) { | |
MutableDocument document = new MutableDocument("map-" + cnt, map); | |
database.save(document); | |
++cnt; | |
} | |
// or | |
cnt = 0; | |
SomeClass[] someClasses = mapper.readValue(json, SomeClass[].class); | |
for (SomeClass someClass: someClasses) { | |
Map properties = mapper.convertValue(someClass, Map.class); | |
MutableDocument document = new MutableDocument("class-" + cnt, properties); | |
database.save(document); | |
++cnt; | |
} | |
for (int nn = 0; nn < cnt; ++nn) { | |
Log.d("ArrayStore - map: ", database.getDocument("map-" + nn).toMap().toString()); | |
Log.d("ArrayStore - class: ", database.getDocument("class-" + nn).toMap().toString()); | |
} | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
} | |
static class SomeClass { | |
public String id; | |
public int val; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment