Kotlin Moshi 从资产中加载 Json
Kotlin Moshi Load Json from assets
我正在尝试使用 moshi 将资产 Json 文件加载到我的项目中。但是,我不断收到以下错误:
com.squareup.moshi.JsonEncodingException: Use JsonReader.setLenient(true) to accept malformed JSON at path $
我应该如何将以下 Json 加载到我的项目中?
json_file.json
[
{
"Name": "Show title",
"Description": "desc",
"Artwork": "link",
"URL": "feed url"
},
{
"Name": "Show title",
"Description": "desc",
"Artwork": "link",
"URL": "feed url"
}
]
这是我做的:
JsonUtil
object JsonUtil {
fun getAssetPodcasts(context: Context): List<JsonPodcast>? {
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val listType = Types.newParameterizedType(List::class.java, JsonPodcast::class.java)
val adapter: JsonAdapter<List<JsonPodcast>> = moshi.adapter(listType)
val file = "json_file.json"
val myjson = context.assets.open(file).bufferedReader().use{ it.readText()}
return adapter.fromJson(myjson)
}
@JsonClass(generateAdapter = true)
data class JsonPodcast(
val Name: String,
val Description: String,
val Artwork: String,
val URL: String
)
}
我的活动
getAssetPodcasts(this)
如有任何帮助,我们将不胜感激!
我终于设法修复了它。对于任何可能发现自己处于相同情况的未来人,这就是我所做的:
虽然 json 看起来很好,但肯定有一些错误的编码。我将 json 上传到 jsoneditoronline,然后再次导出。加载它,现在代码工作正常。
最后,您可以检查调试的其他内容;
- 资产文件是否正确打开?
- 依赖关系是否正确?
- 您是否将
.add(KotlinJsonAdapterFactory())
添加到 moshi 对象?
- listType(如果适用)是否正确?
- 数据class正确吗?
快乐编码(再次)!
如果您为数据使用生成适配器注释,则不需要 KotlinJsonAdapterFactory() 类。
我正在尝试使用 moshi 将资产 Json 文件加载到我的项目中。但是,我不断收到以下错误:
com.squareup.moshi.JsonEncodingException: Use JsonReader.setLenient(true) to accept malformed JSON at path $
我应该如何将以下 Json 加载到我的项目中?
json_file.json
[
{
"Name": "Show title",
"Description": "desc",
"Artwork": "link",
"URL": "feed url"
},
{
"Name": "Show title",
"Description": "desc",
"Artwork": "link",
"URL": "feed url"
}
]
这是我做的:
JsonUtil
object JsonUtil {
fun getAssetPodcasts(context: Context): List<JsonPodcast>? {
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
val listType = Types.newParameterizedType(List::class.java, JsonPodcast::class.java)
val adapter: JsonAdapter<List<JsonPodcast>> = moshi.adapter(listType)
val file = "json_file.json"
val myjson = context.assets.open(file).bufferedReader().use{ it.readText()}
return adapter.fromJson(myjson)
}
@JsonClass(generateAdapter = true)
data class JsonPodcast(
val Name: String,
val Description: String,
val Artwork: String,
val URL: String
)
}
我的活动
getAssetPodcasts(this)
如有任何帮助,我们将不胜感激!
我终于设法修复了它。对于任何可能发现自己处于相同情况的未来人,这就是我所做的:
虽然 json 看起来很好,但肯定有一些错误的编码。我将 json 上传到 jsoneditoronline,然后再次导出。加载它,现在代码工作正常。
最后,您可以检查调试的其他内容;
- 资产文件是否正确打开?
- 依赖关系是否正确?
- 您是否将
.add(KotlinJsonAdapterFactory())
添加到 moshi 对象? - listType(如果适用)是否正确?
- 数据class正确吗?
快乐编码(再次)!
如果您为数据使用生成适配器注释,则不需要 KotlinJsonAdapterFactory() 类。