Erw*_*erg 8 json android-assets kotlin moshi
我正在尝试使用 moshi 将资产 Json 文件加载到我的项目中。但是,我不断收到以下错误:
com.squareup.moshi.JsonEncodingException:使用 JsonReader.setLenient(true) 在路径 $ 处接受格式错误的 JSON
我应该如何将以下 Json 加载到我的项目中?
json_file.json
[
{
"Name": "Show title",
"Description": "desc",
"Artwork": "link",
"URL": "feed url"
},
{
"Name": "Show title",
"Description": "desc",
"Artwork": "link",
"URL": "feed url"
}
]
Run Code Online (Sandbox Code Playgroud)
这就是我所做的:
实用程序
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
)
}
Run Code Online (Sandbox Code Playgroud)
我的活动
getAssetPodcasts(this)
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激!
我终于设法修复它。对于未来可能遇到相同情况的任何人,这就是我所做的:
虽然 json 看起来很完美,但肯定有一些错误的编码。我将json上传到jsoneditoronline,然后再次导出。加载它,现在代码工作得很好。
最后,您可以检查以进行调试的其他内容;
.add(KotlinJsonAdapterFactory())到 moshi 对象了吗?快乐编码(再次)!