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
}
CodePudding user response:
Can you try like this:
data class OrderRecievedData(
val orderPlacedData: OrderPlacedData
)
data class OrderPlacedData (
val createdAt: String,
val lastUpdated: String,
@Json(name = "orderId")
val orderID: String,
val orderedItems: OrderedItems,
@Json(name = "userId")
val userID: String,
val status: String
)
data class OrderedItems (
val quantity: Int,
val price: Int,
val id: String
)
CodePudding user response:
use this data class
data class Response(
@field:SerializedName("orderPlacedData")
val orderPlacedData: OrderPlacedData? = null
)
data class OrderPlacedData(
@field:SerializedName("createdAt")
val createdAt: String? = null,
@field:SerializedName("lastUpdated")
val lastUpdated: String? = null,
@field:SerializedName("orderId")
val orderId: String? = null,
@field:SerializedName("orderedItems")
val orderedItems: OrderedItems? = null,
@field:SerializedName("userId")
val userId: String? = null,
@field:SerializedName("status")
val status: String? = null
)
data class OrderedItems(
@field:SerializedName("quantity")
val quantity: Int? = null,
@field:SerializedName("price")
val price: Int? = null,
@field:SerializedName("id")
val id: String? = null
)