Android Retrofit 2 Json api call


#1

I am trying to post & get data using json using retrofit 2. could someone help where should i start.
any references or links are helpful…


#2

This is from a working app, with the serial numbers filed off. Not Android, but should at least get you started:

package rest

import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path

data class Thing(
        val id: Int
        // Put additional fields here to support the return type of your REST call
)

interface MyRetrofitApi {
    @GET("/thing/{id}")
    fun getThing(@Path("id") id: Int): Call<Thing>
}

object RetrofitExample {

    fun GetThing(baseUri: String, id: Int) {
        val retrofit = Retrofit.Builder()
                .baseUrl("http://${baseUri}/")
                .addConverterFactory(JacksonConverterFactory.create(
                        jacksonObjectMapper()
                                .registerModule(JavaTimeModule())
                ))
                .build()

        val service = retrofit.create(MyRetrofitApi::class.java)
        val response = service.getThing(id).execute()
    }
}

Edit: updated with a more realistic-looking rest endpoint path.