0

After running the following line of code trying to pass a JSON string:

        var test = String(tempstore, Charset.forName("US-ASCII"))

        var gson = Gson()
        var testmodel = gson.fromJson(test, AuthoriseReq::class.java)

The JSON String is as follows :

{
  "transaction": {
    "id": "5f9a1239-0bdc-4ad6-84e0-f685cfa836f9",
    "timestamp": "2019-07-04T08:42:37.9830577+02:00"
  },
  "user": {
    "username": "trt",
    "passwordHash": "juju"
  },
  "terminal": {
    "terminalId": "juju",
    "site": {
      "id": "juju"
    }
  }
}   

The data class are as follow, also to note is that I have included empty constructors in my data classes:

 data class AuthoriseReq(
            @SerializedName("transaction") val transaction: Transaction,
            @SerializedName("user") val user: User,
            @SerializedName("terminal") val terminal: Terminal)
    {
        constructor() : this(Transaction(), User(), Terminal())
    }


 data class Terminal(
            @SerializedName("terminalId") var terminalId: String,
            @SerializedName("site") var site: Site)
            {
             constructor() : this("",  Site())
            }

    data class Transaction(
            @SerializedName("id")   var id: String,
            @SerializedName("timestamp")   var timestamp:DateTime)
    {
        constructor(): this("", DateTime())
    }

data class Site(
        @SerializedName("id")   var id: String)
{
    constructor():this("")
}

data class User(
        @SerializedName("username")   var username: String ,
        @SerializedName("passwordHash")   var passwordHash : String )
{
    constructor(): this("","")
}

However, I keep on getting the following error when the JSON parsing is attempted :

 Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 74 path $.transaction.timestamp
2
  • please see my answer & please accept my answer, if it works for you. Thanks. Commented Jul 4, 2019 at 7:56
  • @ahmedaljubair will do so Commented Jul 4, 2019 at 7:58

1 Answer 1

1

Replace the following

@SerializedName("timestamp")   var timestamp:DateTime)

with

@SerializedName("timestamp")   var timestamp : String )

This should resolve the error since "2019-07-04T08:42:37.9830577+02:00" is a String in the provided JSON string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.