2
{
"error": false,
"total": "20",
"total_page_no": 1,
"current_page_no": 1,
"data": [
    {
        "id": "4241",
        "row_order": "0",
        "name": "Shivaji Ponni Rice",
        "tax_id": "1",
        "slug": "Shivaji Ponni Rice",
        "category_id": "52",
        "subcategory_id": "196",
        "indicator": "1",
        "manufacturer": null,
        "made_in": "Shivaji Ponni Rice",
        "return_status": "1",
        "cancelable_status": "1",
        "till_status": "received",
        "image": "http://www.pasumai.co.in/upload/default-image/default-image.png",
        "other_images": [],
        "description": "The best variety of rice is determined by its amount of usage. In that aspect, The Shivaji brand Matured variety of rice is highly recommended for every household. It is manufactured in the special unit and this variety is the rice matured between the months of august of one year to June of the succeeding year. It can be easily cooked and hence saves time. Perfect in shape, it is easy to digest and is suitable for any family possessing people of all age groups. Nevertheless, they produce a surplus since it is the matured variety of rice. Used by most of the families makes it the highest-selling variety of rice",
        "status": "1",
        "popular": "0",
        "date_added": "2022-07-24 07:50:28",
        "return_max_days": "0",
        "tax": "0",
        "price": "1500",
        "tax_title": "GST",
        "tax_percentage": "0",
        "is_favorite": false,
        "is_notify_me": false,
        "variants": [
            {
                "id": "7477",
                "product_id": "4241",
                "type": "packet",
                "measurement": "26",
                "measurement_unit_id": "1",
                "price": "1500",
                "discounted_price": "1350",
                "serve_for": "Available",
                "stock": "20",
                "stock_unit_id": "6",
                "image": "upload/default-image/default-image.png",
                "moq": "5",
                "varient_status": "1",
                "measurement_unit_name": "kg",
                "stock_unit_name": "pcs",
                "cart_count": "0",
                "is_notify_me": false
            }
        ]
    },
    {
        "id": "4243",
        "row_order": "0",
        "name": "Semmoli Kichadi Ponni",
        "tax_id": "1",
        "slug": "Semmoli Kichadi Ponni",
        "category_id": "52",
        "subcategory_id": "196",
        "indicator": "1",
        "manufacturer": null,
        "made_in": "Semmoli Kichadi Ponni",
        "return_status": "1",
        "cancelable_status": "1",
        "till_status": "received",
        "image": "http://www.pasumai.co.in/upload/default-image/default-image.png",
        "other_images": [],
        "description": "Nei Kichadi Ponni rice is best suited for all occasions. It is well known for premium quality, light weight, excellent aroma and taste. Its gluten free, does not contain any artificial flavours or preservatives",
        "status": "1",
        "popular": "0",
        "date_added": "2022-07-24 07:50:28",
        "return_max_days": "0",
        "tax": "0",
        "price": "1600",
        "tax_title": "GST",
        "tax_percentage": "0",
        "is_favorite": false,
        "is_notify_me": false,
        "variants": [
            {
                "id": "7474",
                "product_id": "4243",
                "type": "packet",
                "measurement": "26",
                "measurement_unit_id": "1",
                "price": "1600",
                "discounted_price": "1420",
                "serve_for": "Available",
                "stock": "20",
                "stock_unit_id": "6",
                "image": "upload/default-image/default-image.png",
                "moq": "5",
                "varient_status": "1",
                "measurement_unit_name": "kg",
                "stock_unit_name": "pcs",
                "cart_count": "0",
                "is_notify_me": false
            }
        ]
    }
]                   
  }

This is My Api Response..i am trying to get the response from retrofit and add the variants list into my room database .. for that i need to take all the variants from this response

I am trying to get all variants and put them in arraylist...how to do that using for loop...Is there any other way to get all variants inside data using Data Structure and Algorithms , means how it is

This is how i get my Api Response :

  fun productlist() = viewModelScope.launch(Dispatchers.IO) {
    productist.collectLatest {
        when(it) {
            Resource.Empty -> {
                Log.e("catdata",""+"empty")
            }
            is Resource.Failure -> {
                Log.e("catdata",""+"failure")
            }
            Resource.Loading -> {

            }
            is Resource.Success -> {
                val response = it.value
                productsDao.insertProducts(response.data)
            }
        }
    }
}
SasidharanIOS
  • 252
  • 1
  • 3
  • 12
  • Please Check Below link https://stackoverflow.com/questions/44986626/android-room-database-how-to-handle-arraylist-in-an-entity – Hanif Shaikh Aug 31 '22 at 08:01
  • Please Check Below link https://stackoverflow.com/questions/44986626/android-room-database-how-to-handle-arraylist-in-an-entity – Hanif Shaikh Aug 31 '22 at 08:02

1 Answers1

0

I think you have to construct a custom function to parse the JsonString returned by Retrofit @GET query.

You can use an interface like this that returns your above JSON String

//@GET function example
    interface VariantAPI {
    
        @GET("your_api_endpoint")
        suspend fun getVariantJsonString():String .. }

Next, you need some data class to hold the variant info or the data you need from API response. A simple data class with 3 properties is shown below but be sure to add more data points as required.

//data class sample
data class Variant(
    val id: String, .......
    val productId: String,
    val isNotifyMe: Boolean
)

Next you need the function to iterate through the response gotten from the Retrofit client and extract the variant data. I'm assuming you are only interested in Variants Data only in which case you can approach it like this.

  1. Define the function which takes retrofit response as a String parameter
  2. Make a variable to hold the Variants elements
  3. Get the JsonObject passing in JSON String parameter
  4. Get the data JSON array reference from the above JsonObject
  5. Iterate through data Array objects
  6. Get the current object inside the data array
  7. Get the variant array reference from the current object
  8. Apply a nested for-EachLoop variant array reference
  9. Get the anonymous object inside the variant array
  10. Collect the relevant data points passing in the respective key
  11. Construct a Variant object with the above data points
  12. Add the variant object to the mutable list
  13. Lastly return the variants list
//custom function to parse Retrofit's response into Variant list
fun parseJsonString(jsonString: String): List<Variant> {

    //lists
    val variantsList = mutableListOf<Variant>()

    //get JsonObject passing in jsonString parameter
    val jsonObject = JSONObject(jsonString)
    //get the data json array reference
    val dataJsonArray = jsonObject.getJSONArray("data")

    //iterate through dataJsonArray objects

    (0 until dataJsonArray.length()).forEach { i ->

        //get the current object
        val dataObject = dataJsonArray.getJSONObject(i)

        //get variantArray
        val variantArray = dataObject.getJSONArray("variants")

        //secondary iteration through the variantArray
        (0 until variantArray.length()).forEach { variantObj ->

            //get anonymous object
            val currentObject = variantArray.getJSONObject(variantObj)

            //data points
            val id = currentObject.getString("id")
            val productId = currentObject.getString("product_id")
            val isNotifyMe = currentObject.getBoolean("is_notify_me")

            //construct variant object from the above data points
            val variant = Variant(id, productId, isNotifyMe)

            //add the created variant object
            variantsList.add(variant)

        }
    }
    //return the variant objects list
    return variantsList
}

You can then use this function somewhere in your Repository class to parse the Json Response received from Retrofit and then proceed to cache the info in the ROOM Database.

class RepositoryImpl(api:YourAPI){ ....
 
    val remoteData: List<Variant>? = try {
             val jsonString = api.getVariantJsonString()
             //call the above fxn and pass the JsonString from Retrofit
             parseJson(jsonString)
    
                } catch(e:Exception) { ... null}
Tonnie
  • 4,865
  • 3
  • 34
  • 50
  • just now i updated my that how i get the response from retrofit...would you please tell me that how can i get the variant list alone in success method..i already took the products in kept in array ..same like i want all variants using for loop @Tonnie – SasidharanIOS Aug 31 '22 at 09:56
  • For that I will have to see your entire code, drop me the GitHub link – Tonnie Aug 31 '22 at 14:00
  • 1
    for (i in 0 until response.data.size) { val product: Products = response.data.get(i) for (j in 0 until product.variants.size) { val variants: Variants = product.variants.get(j) productsDao.insertVariants(variants) } } – SasidharanIOS Sep 01 '22 at 02:33
  • 1
    This is tje answer i expect @Tonnie – SasidharanIOS Sep 01 '22 at 02:33
  • Awesome, seems like you have figured out the answer, good work. – Tonnie Sep 01 '22 at 04:27