I have a problem with importing data from json to Android Realm. I get "Could not map | Expected JsonObject instead of Integer" error.
I know it works when I put the json object instead of foreign key but I want to use foreign key. This is my schema: Database
And this is my models:
Category:
@RealmClass
public class Category extends RealmObject {
@PrimaryKey
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Product:
@RealmClass
public class Product extends RealmObject {
@PrimaryKey
private int id;
private String name;
private Category category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
And this is my json file for importing file:
categories.json:
[
{
"id": 1,
"name": "Price"
},
{
"id": 2,
"name": "Site"
}
]
products.json:
[
{
"id": 1,
"name": "Price Product",
"category": 1
},
{
"id": 2,
"name": "Site Product",
"category": 2
}
]
Import.java
Realm db = Realm.getInstance(mContext);
db.beginTransaction();
try {
db.createOrUpdateAllFromJson(Category.class, App.loadJSONFromAsset(mContext, "categories"));
db.createOrUpdateAllFromJson(Product.class, App.loadJSONFromAsset(mContext, "products"));
db.commitTransaction();
} catch (Exception e) {
db.cancelTransaction();
e.printStackTrace();
}
db.close();
if I change the products.json to below json, it works.
[
{
"id": 1,
"name": "Price Product",
"category": {
"id": 1,
"name": "Price"
}
},
{
"id": 2,
"name": "Site Product",
"category": {
"id": 1,
"name": "Site"
}
}
]