Home > Net >  Fetch list of transactions from json
Fetch list of transactions from json

Time:11-28

In my task I need to fetch some data.

I made UserModelClass where I put some data classes:

      "id": "1",
      "IBAN": "HR123456789012345678901",
      "amount": "2.523,00",
      "currency": "HRK",
      "transactions": [
        {
          "id": "1",
          "date": "25.01.2016.",
          "description": "Uplata 1",
          "amount": "15,00 HRK"
        },
        {
          "id": "2",
          "date": "17.02.2016.",
          "description": "Uplata 2",
          "amount": "50,00 HRK",
          "type": "GSM VOUCHER"
        }]

This is my code:

data class UserModelClass (
    val user_id:String,
    val accounts: List<AccountsList>
)

data class AccountsList(
    val id: String,
    val IBAN: String,
    val amount: String,
    val currency: String,
    val transactions: List<transactionsList>

)

data class transactionsList(
    val id: String,
    val date: String,
    val description: String,
    val amount: String
    //
)

Problem is that some transactions have type and some don't have it. I tried to make one more data class transactionsList where I put val type but there can be only one data class with the same name.

CodePudding user response:

You can add a nullable field for when the type is not present.

data class transactionsList(
    val id: String,
    val date: String,
    val description: String,
    val amount: String,
    val type: String?
)

The ? there means that type can be null (and will be when it is not present in the json).

You could also give it a default value instead, like this:

data class transactionsList(
    val id: String,
    val date: String,
    val description: String,
    val amount: String,
    val type: String = "not given" //or whatever value you want
)

In this example, when the json doesn't have type, it will be automatically set as not given.

  • Related