Search code examples
androidjsonkotlinpojoandroid-networking

Json Response conversion Stuff in Android


Below is the model class I am created for my json response :

data class MyModelClass(
        val one: String,
        val two: String,
        val three: String,
        val four: Int,
        val tempCurrentCharge: List<CurrentCharge>,
        val tempCurrentDischarge: List<CurrentDischarge>
)

Now, above you can see that I am getting Arrays of List<CurrentCharge> and List<CurrentDischarge> in my Json response as below :

"tempCurrentCharge": [
  {
    "temp": -600,
    "cRating": 0
  },
  {
      "temp": 0,
      "cRating": 10
  }
]

Now, I can successfully parse the json response and saved it in my local db (as per my need).

Now I have two feilds in my local db table, one is for CurrentCharge and another if for CurrentDischarge.

I have to save the whole json string as value in this. Currently It saved as Object.toString() Instead I want to save the whole json string which is as shared above.

The issue is since I have created the pojo class for json parsing, Its parsing the data for tempCurrentCharge and tempCurrentDischarge automatically.

But I want to store the values of json String in it. So, What I have done is: changed the type of both the variables as String

But then it given me type casting error as :

"BEGIN_ARRAY... found String".

So, Anyone please suggest me how can I achive storing above jsonArray as string json in my local room db field?

Thanks in Advance.


Solution

  • Let your data class remain as it is, the error you are receiving is justified because in the response you are getting an array while you have changed the type in your data class to a String and thus the following error

    "BEGIN_ARRAY... found String".

    Coming to what you need, you can simply convert it back to JSON once it is parsed and save it then. You will need Gson library and I am sure it is added to your project. If not please add it.

    What next you will need is to simply do is this. I am assuming you have an object of the BatteryConfigurationDetails class

    val batteryConfig = BatteryConfigurationDetails()
    
    val tempCurrentChargeJson = Gson().toJson(batteryConfig.tempCurrentCharge)
    val tempCurrentDischargeJson = Gson().toJson(batteryConfig.tempCurrentDischarge)
    

    To convert it back you can use the following function

    Gson().fromJson()
    

    Add the following if you do not have the library already

    implementation 'com.google.code.gson:gson:2.8.7'