mchd
mchd

Reputation: 3163

How do I parse JSON in Kotlin without a 3rd party parser?

I'm trying to parse JSON in Kotlin manually without the use of a 3rd party JSON parser (unlike the other questions that were already asked). I'm building Udacity's "popular movies" app with the themovieDb api to be comfortable building Android apps with Kotlin because I've never used Kotlin before. For the first section, I want to display the movie posters in a 3 column grid. This is the position of the poster_path object in the API:

{
  ...
  "poster_path": "...jpg",
}

In Java, I would normally create a JSONObject and then use methods like getString or getInt on that object to retrieve the specific information I need. How does one go about this in Kotlin?

What I have so far is an app that repeats the same image on a 3 column grid using Recyclerview:

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val recyclerView = findViewById<RecyclerView>(R.id.recycler_view);
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.layoutManager = GridLayoutManager(this, 3);
        recyclerView.adapter = RecyclerAdapter()
    }

    data class Response(val movieTitle: String,
                        val moviePoster: Int,
                        val overview: String,
                        val ratings: Int,
                        val releaseDate: String,
                        val review: String)
}

Upvotes: 2

Views: 3194

Answers (2)

CommonsWare
CommonsWare

Reputation: 1007544

I am more comfortable parsing the JSON manually, instead of using a parser like GSON or Volley.

I am interpreting this as meaning that you want to pull data out of the JSON, walking the JSON structure yourself, rather than using a JSON parser that populates model objects.

In that case, there is nothing stopping you from using JSONObject in Kotlin, just as you are using Bundle and LinearLayoutManager and RecyclerView in Kotlin. So, val json = JSONObject(jsonText) and stuff should work just fine.

Upvotes: 3

Cililing
Cililing

Reputation: 4763

Exactly the same way like in Java. Code written in Java can run in Kotlin applications. Remember also that Java doesn't support JSON by native and this JSONObject you mentioned is from com.google.gson package.

Upvotes: 1

Related Questions