-1

SOLUTION: How to save nested List<String> in RoomDB on Android


I have the following JSON file

[
  {
    "id":"some_string_id1",
    "name": "some_name1".
    "tags": [
        "tag1",
        "tag2"
    ]
  },
  {
    "id":"some_string_id2",
    "name": "some_name2".
    "tags": []
  },
]

The following is how it's being parsed:

@Entity(tableName = "node_table")
public class NodeItem {
    @PrimaryKey (autoGenerate = false) @NonNull
    public String id;
    @NonNull
    public String name,tags;

    NodeItem(String id, String name, String tags){
        this.id = id;
        this.name = name;
        this.tags = tags;
    }

    @Override
    public String toString() {
        return "NodeItem{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", tags='" + tags + '\'' +
                '}';
    }

    public static List<NodeItem> loadJSON(Context context, String path){
        try{
            InputStream input = context.getAssets().open(path);
            Reader reader = new InputStreamReader(input);
            Gson gson = new Gson();
            Type type = new TypeToken<List<NodeItem>>(){}.getType();
            return gson.fromJson(reader,type);
        }catch (IOException e){
            e.printStackTrace();
            return Collections.emptyList();
        }

    }

The error I get is:

Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY

Is it possible to parse the list as a comma-separated string?

If that's not possible, then how can I save the list into the database?

  • Does this answer your question? [Gson Expected STRING but was BEGIN\_ARRAY?](https://stackoverflow.com/questions/24321975/gson-expected-string-but-was-begin-array) – Rohit5k2 May 06 '22 at 02:58
  • `tags` is an Array but you are parsing it as a string. – Rohit5k2 May 06 '22 at 02:58
  • thanks for the help, but by some miracle, I was able to find the solution I wanted. https://stackoverflow.com/questions/45477889/how-to-save-nested-liststring-in-roomdb-on-android/45477939#45477939 However, this leaves a small problem. How would I save a an empty list? Can I give it a default value? – Stove Games Games May 06 '22 at 03:21

0 Answers0