Skip to content

Instantly share code, notes, and snippets.

@milechainsaw
Last active May 19, 2020 16:44
Show Gist options
  • Save milechainsaw/988a8bca428abfd7fda0f93ebdb43f6e to your computer and use it in GitHub Desktop.
Save milechainsaw/988a8bca428abfd7fda0f93ebdb43f6e to your computer and use it in GitHub Desktop.
ObjectBox converter for List<String> properties in your Kotlin data model. http://objectbox.io/
package com.test.objectbox.models
import io.objectbox.annotation.Convert
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
@Entity data class Article(
@Id var id: Long = 0,
@Convert(converter = StringListConverter::class, dbType = String::class)
var strings: List<String>? = null,
)
package com.test.objectbox.converters
import io.objectbox.converter.PropertyConverter
class StringListConverter : PropertyConverter<List<String>, String> {
override fun convertToEntityProperty(databaseValue: String?): List<String> {
if (databaseValue == null) return ArrayList()
return databaseValue.split(",")
}
override fun convertToDatabaseValue(entityProperty: List<String>?): String {
if (entityProperty == null) return ""
if (entityProperty.isEmpty()) return ""
val builder = StringBuilder()
entityProperty.forEach { builder.append(it).append(",") }
builder.deleteCharAt(builder.length - 1)
return builder.toString()
}
}
@koush
Copy link

koush commented Oct 18, 2018

Was looking for something like this myself. Just a heads up to anyone else that arrived here via Google: this code has a bug if anything in the list of strings is null or contains a comma.

@koush
Copy link

koush commented May 19, 2020

Here's what I use.

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.converter.PropertyConverter;

public class StringListConverter implements PropertyConverter<List<String>, String> {
    @Override
    public List<String> convertToEntityProperty(String databaseValue) {
        if (databaseValue == null)
            return new ArrayList<>();
        try {
            JSONArray array = new JSONArray(databaseValue);
            ArrayList<String> ret = new ArrayList<>();
            for (int i = 0; i < array.length(); i++) {
                ret.add(array.getString(i));
            }
            return ret;
        }
        catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public String convertToDatabaseValue(List<String> entityProperty) {
        try {
            if (entityProperty == null)
                return null;
            return new JSONArray(entityProperty).toString();
        }
        catch (Exception e) {
            return null;
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment