Search code examples
javaandroidjsonkotlingson

Unable to convert Json to POJO using Gson


Here is my response:

{
  "orderPlacedData": {
    "createdAt": "2022-06-22T00:34:25.833Z",
    "lastUpdated": "2022-06-22T00:34:25.833Z",
    "orderId": "62b26391e5ddd5001620cd07",
    "orderedItems": {
      "quantity": 1,
      "price": 654,
      "id": "61f4da753627fc0016dfec5a"
    },
    "userId": "6294d73a789e677d84d8e282",
    "status": "PENDING_CONFIRMATION"
  }
}

Here are my data classes:


@Parcelize
data class OrderRecievedData(
    val orderPlacedData: OrderPlacedData
):Parcelable


@Parcelize
data class OrderPlacedData(
    @PrimaryKey(autoGenerate = false)
    val orderId: String,
    val status: String,
    var userId: String,
    val orderedItems: OrderPlaceDataItem,
    val createdAt: String,
    val lastUpdated: String
) : Parcelable 


@Parcelize
data class OrderPlaceDataItem(
    val id: String,
    val quantity: Int,
    val price:Int
) : Parcelable

I'm trying to convert the above string to POJO but I'm getting this java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 21 path $.orderPlacedData

I'm not sure why I'm getting this error since my Json is beginning from a { not a ".

My code for converting the above string to POJO:

val data = try {
        val jsonString = Gson().toJson(message.data)
        Gson().fromJson(jsonString,OrderRecievedData::class.java)

    } catch (e: Exception) {
        Log.d(TAG, "onMessageReceived: exception $e")
        null
    }

Solution

  • I finally solved what the problem was. I was converting the data to Json before converting it to POJO. But since I was already getting the data as Json I just needed it to convert it to string and it worked.

    val data = try {
        Gson().fromJson(message.data.toString(),OrderRecievedData::class.java)
    
    } catch (e: Exception) {
        Log.d(TAG, "onMessageReceived: exception $e")
        null
    }