Last active
May 19, 2020 16:44
-
-
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/
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.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, | |
) |
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.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() | |
} | |
} |
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
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.