Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Moshi Load Json from assets

I'm trying to load an assets Json file into my project with moshi. However, i keep getting the following error:

com.squareup.moshi.JsonEncodingException: Use JsonReader.setLenient(true) to accept malformed JSON at path $

How should I load the following Json into my project?

json_file.json

[
  {
    "Name": "Show title",
    "Description": "desc",
    "Artwork": "link",
    "URL": "feed url"
  },
  {
    "Name": "Show title",
    "Description": "desc",
    "Artwork": "link",
    "URL": "feed url"
  }
]

This is what I did:

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
    )
}

myactivity

getAssetPodcasts(this)

Any help would be greatly appreciated!

like image 738
Erwin van den Berg Avatar asked Jul 25 '19 13:07

Erwin van den Berg


2 Answers

I finally managed to fix it. For any future people that might find themselves in the same situation, here's what i did:

Although the json looks perfectly fine, there must have been some wrong encoding. I uploaded the json to jsoneditoronline and then exported it again. Loaded it, and now the code works just fine.

Lastly, other things you could check to debug;

  1. Did the asset file open correctly?
  2. Are the dependencies correct?
  3. Did you add .add(KotlinJsonAdapterFactory()) to the moshi object?
  4. Is the listType - if applicable - correct?
  5. And is the data class correct?

Happy coding (again)!

like image 116
Erwin van den Berg Avatar answered Nov 16 '22 02:11

Erwin van den Berg


You don't need KotlinJsonAdapterFactory() if you use generate adapter annotations for data classes.

like image 45
Alex Maryin Avatar answered Nov 16 '22 03:11

Alex Maryin