This example shows how to insert a JSON string or Object in Realm database. Below code uses Java InputStream and InputStream with createObjectFromJson and createAllFromJson methods to insert JSON data to Realm database.
— You can add a JSON object that maps to a RealmObject to Realm.
— The JSON object can be a String, a JSONObject or an InputStream.
— Realm will ignore any properties in the JSON not defined by the RealmObject.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// A RealmObject that represents a city public class City extends RealmObject { private String city; private int id; // getters and setters... } // Insert from a JSON String try (Realm realm = Realm.getDefaultInstance()) { realm.executeTransaction(real -> { real.createObjectFromJson(City.class, "{ city: \"Amravati\", id: 1 }"); }); } // Insert multiple JSON items using an InputStream try (Realm realm = Realm.getDefaultInstance()) { realm.executeTransaction(real -> { try { InputStream inputStream = new FileInputStream(new File("path_to_json_file")); real.createAllFromJson(City.class, inputStream); } catch (IOException e) { throw new RuntimeException(e); } }); } |