房间类型地图转换器 [英] Room TypeConverter for map
本文介绍了房间类型地图转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您将如何编写Map的TypeConverter?我的方法是由Moshi做到
How would you write TypeConverter for Map? My approach was to do it by Moshi
class Converters() {
val moshi = Moshi
.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val mapOfStringsType = Types.newParameterizedType(Map::class.java, String::class.java, String::class.java)
val mapOfStringsAdapter = moshi.adapter<Map<String, String>>(mapOfStringsType)
@TypeConverter
fun stringToMap(data: String): Map<String, String> {
return mapOfStringsAdapter.fromJson(data).orEmpty()
}
@TypeConverter
fun mapToString(map: Map<String, String>): String {
return mapOfStringsAdapter.toJson(map)
}
}
但是,它闻起来是因为我无法通过Converters()
构造函数注入Moshi.
而且,恐怕也不是最好的表现.
However, it smells, because I can't inject Moshi by Converters()
constructor.
And, I'm afraid, it's not the best performance either.
推荐答案
我通常将gson用作Room TypeConverters.它提供了适用于所有对象类型的简单实现:
I usually use gson for Room TypeConverters. It allows for simple implementation that will work for all object types:
public class StringMapConverter {
@TypeConverter
public static Map<String, String> fromString(String value) {
Type mapType = new TypeToken<Map<String, String>>() {
}.getType();
return new Gson().fromJson(value, mapType);
}
@TypeConverter
public static String fromStringMap(Map<String, String> map) {
Gson gson = new Gson();
return gson.toJson(map);
}
}
这篇关于房间类型地图转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文