how call data from json like this with Retrofit library - android

i tried this :
interface MYAPI {
#GET("get-languages")
fun getdata() : Call<List<Data.Language>>
}
this is my api service
{
"message": "success",
"data": {
"language": [ {"id": 5,
"name": "English",
"icon": "19638193-en.png"
},
{
"id": 6,"name": "turkish","icon": "19638199-tr.png"}
]
}
}

{
"message":"success",
"data":{
"language":[]
}
}
Share your response model but you will need the "data" attribute that is a language model. If you use directly the language model then won´t works.
So a possible data could be:
data class LanguageResponse(val id: Int, val name: String, val icon: String)
data class LanguagesResponse(val language: List<LanguageResponse>)
data class DataLanguageResponse(val data: LanguagesResponse)
And your call:
interface MYAPI {
#GET("get-languages")
fun getdata() : Call<DataLanguageResponse>
}

Solved..
i add to AndroidManifest :
android:usesCleartextTraffic="true"

Related

Android - Convert json which has uncertain keys to map using kotlin

I have a json like this. I need to convert it to data class
{
"0": {
"id": "111",
"type": "1",
"items": [
{
"name": "Jack",
"value": "26",
"age": "0.0"
},
{
"name": "Lisa",
"value": "18",
"age": "1.0"
}
]
},
"1": {
"id": "222",
"type": "2",
"items": [
{
"name": "Brown",
"value": "23",
"age": "30.0"
},
{
"name": "Andy",
"value": "18",
"age": "23.0"
}
]
},
"className": "A01"
}
I define the following data class
data class Orders (
val className: String?,
val classes: Map<String, EachClass>
)
data class EachClass (
val id: String,
val type: String,
val items: List<Person>
)
data class Person (
val name: String,
val value: String,
val age: String
)
And the result always show
className=> A01, classes=> null
I searched the stackoverflow and they said using TypeToken. But I have a field called "className" which cannot be convert with EachClass object
val type = object : TypeToken<EachClass>() {}.type
val obj = Gson().fromJson(data, EachClass::class.java)
and I found TypeToken with HashMap<String, Object> is working but its ugly and I need to convert to data class myself.
I'm appreciate if someone can tell me the correct way to convert the json. Thanks!
Gson does not provide built-in functionality for this specific situation so you need to do some manual conversion, but luckily for your use case it is not that much work. The following approach should work:
Parse the JSON as Gson's JsonObject
Remove the className member and store it for later
Parse the JsonObject as Map<String, EachClass>
Construct an Orders instance from the results from step 2 and 3
The complete solution could look like this:
object OrdersDeserializer: JsonDeserializer<Orders> {
private val classesType = object: TypeToken<Map<String, EachClass>>() {}.type
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Orders {
val jsonObject = json.asJsonObject
val className = jsonObject.remove("className").asJsonPrimitive.asString
val classes: Map<String, EachClass> = context.deserialize(jsonObject, classesType)
return Orders(className, classes)
}
}
You would then register it like this:
val gson = GsonBuilder()
.registerTypeAdapter(Orders::class.java, OrdersDeserializer)
.create()
Alternatively you could also convert it to a regular class and use Gson's #JsonAdapter annotation on the Orders class to avoid having to register the deserializer manually.
Note: Normally is recommended to prefer TypeAdapter over JsonSerializer / JsonDeserializer to allow streaming the data for better performance. However, since you need to work on a JsonObject here anyway (therefore non-streaming) using TypeAdapter does not provide an advantage here and might only complicate the implementation a bit.

Retrofit parse JSON into different models

I want to parse JSON like below:
{
"result": 0,
"list": [
{
"id": 58,
"type": "58",
"name": "fooGroup",
"foos": {
"id": "1",
"name": "33",
}
]
}
If I define models like this:
data class Response(val result: Int,
#SerializedName("list") val fooGroup: List<FooGroupResponse>)
data class FooGroupResponse(val id: Int, val type: String, val name: String,
#SerializedName("foos") val fooGroup: List<Foo>?)
data class Foo(val id: Int, val name: String)
then everything works fine.
Right now I want to take these out as a model:
"id": 58,
"type": "58",
"name": "fooGroup",
That is add one more model FooGroup like below:
data class Response(val result: Int,
#SerializedName("list") val fooGroup: List<FooGroupResponse>)
data class FooGroupResponse(val fooGroup: FoolGroup,
#SerializedName("foos") val fooGroup: List<Foo>?)
data class Foo(val id: Int, val name: String)
data class FooGroup(val id: Int, val type: String, val name: String)
But there's no #SerializedName can be set for FooGroup, is it possible?
Thanks.
I think you will have to restructure your JSON. The parser is going to make a faithful representation of the JSON string as a Java object. Your first example is the faithful representation. What you want to do is not faithful to the JSON received.
{
"result": 0,
"list": [
{
"fooGroup": {
"id": 58,
"type": "58",
"name": "fooGroup"
},
"foos": [
{
"id": "1",
"name": "33"
}
]
}
]
}
BUT you can do it manually where you parse the object yourself. Here is a how to with GSON but it should be easily convertible if you prefer another lib.
https://www.woolha.com/tutorials/retrofit-2-define-custom-gson-converter-factory
Simply pull "id", "type", "name" from the JSON as its deserializing and make a composite data class.
data class FooGroup(val id: Int, val type: String, val name: String)
//You deserialize you JSON into a List of Foos
data class Foos(val foo: Foo, val fooGroup : FooGroup)

Convert JSON to POJO with different data type

I have this response, i have problem when i want to convert to pojo.
"equity": {
"0": {
"name": [
"Abc"
],
"code": [
"3410"
],
"ending_balance": [
301834470
]
},
"1": {
"name": [
"Xyz"
],
"code": [
"2180"
],
"ending_balance": [
0
]
},
"2": {
"name": [
"Pqr"
],
"code": [
"9220"
],
"ending_balance": [
0
]
},
"total_equity": 301834470
}
}
I'm confused about giving the right data type, because there are arrays("0","1","2") that contain objects and "total_equity" that contain number.
I've tried to give the map data type, but it will be error for "total_equity"
var equity: Map<String, EquityDto?>
If you know the solution for this problem please help me. Thank you
You can use
var equity: Map<String, Any>
While accessing the Any Data type u can compare the varrriable type(instance of) and use the value as following
if (valueofMap is Int){
//here is integer value
}
if (valueofMap is yourDataClass){
//your custom class
}
There can be a solution to this, but it will be a lengthy one.
One solution can be to transform the response to Map<String, Any> then you will have to check the type every time you have to use it and it can really annoying when you are using it in multiple classes.
Another solution can be to create a custom Custom Type Adapter which you can pass to the Retrofit Instance in the addConverterFactory method.
To create a custom adapter, you just have to follow the following steps:
Create a model in which you want to store the data. In your case it can be :
data class ApiResponse(
val data: Map<String, EquityDto?>,
val totalEquity:Int
)
Create the Adapter:
class StudentAdapter : TypeAdapter<ApiResponse?>() {
#Throws(IOException::class)
fun read(reader: JsonReader): ApiResponse {
val student:ApiResponse? = null
reader.beginObject()
var fieldname: String? = null
while (reader.hasNext()) {
var token = reader.peek()
if (token == JsonToken.NAME) {
//get the current token
fieldname = reader.nextName()
}
if ("total_equity" == fieldname) {
token = reader.peek()
student?.totalEquity = reader.nextInt()
}else {
token = reader.peek()
student?.data?.set(fieldname.toString(), reader.nextString())
}
}
reader.endObject()
return student
}
#Throws(IOException::class)
fun write(writer: JsonWriter, student: ApiResponse) {
writer.beginObject()
writer.name("data")
writer.value(student.data.toString())
writer.name("totalEquity")
writer.value(student.totalEquity)
writer.endObject()
}
}
If you know a better way to create a type adapter then you can surely use that.

Kotlin Retrofit Error "Expected BEGIN_ARRAY but was BEGIN_OBJECT"

I've read through multiple posts on StackOverflow, but haven't found a solution that fits my problem yet. Could you please help me fix this Retrofit error?
JSON response:
{
"products": [
{
"barcode_number": "8000040000802",
"barcode_type": "EAN",
"barcode_formats": "EAN 8000040000802",
"mpn": "",
"model": "",
"asin": "",
"product_name": "Campari Bitter 25% Vol. 1 L",
"title": "",
"category": "Food, Beverages & Tobacco > Beverages > Alcoholic Beverages > Bitters",
"manufacturer": "Campari",
"brand": "Campari",
"label": "",
"author": "",
"publisher": "",
"artist": "",
"actor": "",
"director": "",
"studio": "",
"genre": "",
"audience_rating": "",
"ingredients": "",
"nutrition_facts": "",
"color": "",
"format": "",
"package_quantity": "",
"size": "",
"length": "",
"width": "",
"height": "",
"weight": "",
"release_date": "",
"description": "",
"features": [],
"images": [
"https://images.barcodelookup.com/19631/196313718-1.jpg"
],
"stores": [
{
"store_name": "Rakuten Deutschland GmbH",
"store_price": "16.50",
"product_url": "https://www.rakuten.de/produkt/campari-bitter-25-vol-1-l-1826679605",
"currency_code": "EUR",
"currency_symbol": "€"
}
],
"reviews": []
}
]
}
Data classes that have been created by the JSON to Kotlin plugin:
data class BaseResponse(
val products: List<Product>
)
Product:
data class Product(
val actor: String,
val artist: String,
val asin: String,
val audience_rating: String,
...
)
Store:
data class Store(
val currency_code: String,
val currency_symbol: String,
val product_url: String,
val store_name: String,
val store_price: String
)
Service:
interface BarcodeLookupApiService {
#GET("products")
suspend fun getArticleData(#Query("barcode") barcode: String,
#Query("key") key: String): List<BaseResponse>
}
Retrofit Builder:
object RetrofitBuilder {
private const val BASE_URL = "https://api.barcodelookup.com/v2/"
private fun getRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val apiService: BarcodeLookupApiService =
getRetrofit().create(BarcodeLookupApiService::class.java)
}
Are the data classes created by the plugin not right? Or should my service not return a list? I've tried returning a simple BaseResponse object but that doesn't work either.
Change your interface as shown below:
interface BarcodeLookupApiService {
#GET("products")
suspend fun getArticleData(#Query("barcode") barcode: String,
#Query("key") key: String): BaseResponse
}
and to get list of products do as shown below:
baseRespose.ProductsList
This will fix your issue. The response is an object with has an array inside object. Hence you are getting error.
In my case I was using Laravel framework to build my web service or Rest Api with Sanctum. Ok the problem was here:
{
"result": {
"message": "Registrado correctamente",
"success": true,
"status": 200,
"error": null
}
}
The GsonConverter queries of brackets yes look here be careful:
{
"result": [
{
"message": "Registrado correctamente",
"success": true,
"status": 200,
"error": null
}
]
I update my backend Api:
$result = [
'message' => 'Registrado correctamente',
'success' => true,
'status' => 200,
'error' => null
];
return response()->json([
'result' => $result,
], 200);
to
return response()->json([
'result' => [$result],
], 200);
See careful I have added brackets [ ] to 'result'. This fixed my problem.
My two data class were this:
#Parcelize
data class RegisterResponseObj(
val message: String,
val success: Boolean,
val status: Int = -1,
val error: String?,
) : Parcelable
data class RegisterResponse(val result: List<RegisterResponseObj>)
The web service:
interface WebService {
#FormUrlEncoded
#Headers("Accept: application/json")
#POST("register")
suspend fun registerUser(#Field("name") name: String,
#Field("email") email: String,
#Field("password")password: String): RegisterResponse
}
Cheers!

How to parse dynamically named jsonarray using Gson and retrofit2?

I have a JSON response, which looks like this:
{
"equipment_layer": [
{
"id": 2,
"name": "Gateway",
"detail": "All gateways"
},
{
"id": 3,
"name": "Node",
"detail": "All Nodes"
},
{
"id": 1,
"name": "Miscellaneous",
"detail": "All miscellaneous assets"
},
{
"id": 4,
"name": "Sensors",
"detail": "All Sensors"
},
{
"id": 5,
"name": "IRM",
"detail": "Installation required material"
},
{
"id": 6,
"name": "Communication",
"detail": "All communication devices such as Cellular Router, ETU etc. which are purely communication"
}
],
"data": {
"1": [
{
"equipment_id": 353,
"item_quantity": 1,
"name": "DC Current Transformer (20mm) (Old)",
"shortcode": "SNS-DCI-CT20m-R1A",
"part_number": "718,804,805,",
"equipment_layer_id": 1,
"equipment_layer_name": "Miscellaneous"
},
{
"equipment_id": 357,
"item_quantity": 1,
"name": "Fuel Sensor - B4 (Old)",
"shortcode": "SNS-FUL-PSR-R1A",
"part_number": "718,810,811",
"equipment_layer_id": 1,
"equipment_layer_name": "Miscellaneous"
}
],
"2": [
{
"equipment_id": 345,
"item_quantity": 1,
"name": "RTU (Old)",
"shortcode": "RAN-RTU-PMCL-R1A",
"part_number": "787,788,789",
"equipment_layer_id": 2,
"equipment_layer_name": "Gateway"
}
],
"3": [
{
"equipment_id": 356,
"item_quantity": 1,
"name": "Battery Analyzer (Product) (Old)",
"shortcode": "RAN-BAM-PMCL-R1A",
"part_number": "787,808,809",
"equipment_layer_id": 3,
"equipment_layer_name": "Node"
}
],
"4": [
{
"equipment_id": 346,
"item_quantity": 1,
"name": "DC Current Transformer (30mm) (Old)",
"shortcode": "SNS-CT-DCI-R1A",
"part_number": "718,792,793",
"equipment_layer_id": 4,
"equipment_layer_name": "Sensors"
},
{
"equipment_id": 350,
"item_quantity": 1,
"name": "AC Block CT (Old)",
"shortcode": "SNS-ACI-BLK-R1A",
"part_number": "718,790,791",
"equipment_layer_id": 4,
"equipment_layer_name": "Sensors"
}
]
}
}
Now the part after the "data" label is dynamic, in a response I can have subarrays of "1", "2" but not of "3" or "4".The POJO of the data inside is same as you can see. So how can I parse this data? I'm using Rerofit2 with Gson.converterfactory. I've tried jsonchema2pojo as well but the data inside the "data" object is not showing up.
I've tried to follow this method:
Parsing Retrofit2 result using Gson with different JSON structures but I can't seem to trigger the UnrwapConverter.
This is my converterfactory implementation:
internal class UnwrappingGsonConverterFactory private constructor(private val gson: Gson) : Converter.Factory() {
override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *> ?{
if (!needsUnwrapping(annotations)) {
return super.responseBodyConverter(type, annotations, retrofit)
}
val typeAdapter = gson.getAdapter(TypeToken.get(type))
return UnwrappingResponseConverter(typeAdapter)
}
private class UnwrappingResponseConverter (private val typeAdapter: TypeAdapter<*>) : Converter<ResponseBody, Any> , AnkoLogger{
#Throws(IOException::class)
override fun convert(responseBody: ResponseBody): Any? {
responseBody.use { responseBody ->
JsonReader(responseBody.charStream()).use({ jsonReader ->
// Checking if the JSON document current value is null
val token = jsonReader.peek()
if (token === JsonToken.NULL) {
return null
}
// If it's an object, expect `{`
jsonReader.beginObject()
var value: Any? = null
// And iterate over all properties
while (jsonReader.hasNext()) {
val data = jsonReader.nextName()
debug("Unwrap Stuff: $data")
when (data) {
"1", "2", "3", "4", "5", "6" -> value = typeAdapter.read(jsonReader)
else ->jsonReader.skipValue()
}
}
// Consume the object end `}`
jsonReader.endObject()
return value
})
}
}
}
companion object {
fun create(gson: Gson): Converter.Factory {
return UnwrappingGsonConverterFactory(gson)
}
private fun needsUnwrapping(annotations: Array<Annotation>): Boolean {
for (annotation in annotations) {
if (annotation is Unwrap) {
return true
}
}
return false
}
}
}
And the interface:
#Retention(AnnotationRetention.RUNTIME)
#Target(AnnotationTarget.FUNCTION)
annotation class Unwrap
My data classes are these:
data class ActivityNodes(#SerializedName("equipment_layer") val equipmentLayer: List<EquipmentLayer>,
#SerializedName("data") val data: nodeData)
data class nodeData (#SerializedName("1") val nodeList: List<dataItem>) <-- this is where I need someway to tell SerializedName that the value can be anything from 1 to 6
data class dataItem(#SerializedName("equipment_id") val equipmentId: Int,
#SerializedName("item_quantity") val itemQuantity: Int,
#SerializedName("name") val name: String,
#SerializedName("shortcode") val shortCode: String,
#SerializedName("part_number") val partNumber: String,
#SerializedName("equipment_layer_id") val equipmentLayerId: Int,
#SerializedName("equipment_layer_name") val equipmentLayerName: String,
var isScanned: Boolean = false )
data class EquipmentLayer(#SerializedName("id") val id: Int,
#SerializedName("name") val name: String,
#SerializedName("detail") val details: String)
For the dynamic JSON, you have to parse the JSON string manually. To get JSON string from retrofit you have to use ScalarsConverterFactory instead of GsonConverterFactory.
Add this dependency:
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
Create Adapter like this:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://echo.jsontest.com")
.addConverterFactory(ScalarsConverterFactory.create())
.build()
Create request method with ResponseBody
public interface MyService {
#GET("/key/value/one/two")
Call<ResponseBody> getData();
}
You can get Json String like this:
MyService service = retrofit.create(MyService.class);
Call<ResponseBody> result = service.getData();
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Now you have to parse the JSON string manually to get your data from JSON.
Hope it helps:)
use below for the part of "data" of json:
Type mapType = new TypeToken<Map<String, List<EqupmentDetail.class>>>() {}.getType(); // define generic type
Map<String, List<EqupmentDetail.class>> result= gson.fromJson(new InputStreamReader(source), mapType);
here define EqipmentDetails class same as your refence
this will definitely work

Categories

Resources