Andrey Danilov
Andrey Danilov

Reputation: 6602

GSON can`t deserialize Kotlin class with custom getter

Well I have a class

class Address {
    var address1: String? = null
}

And simple json

String jsonString = "{\"address1\":\"test\"}";

So all I want to deserialize that, so I just write

    Gson gson = new GsonBuilder().create();
    Address address = gson.fromJson(jsonString, Address.class);

And it works perfectly.

But if I add custom getter

class Address {
    var address1: String? = null
        get() = address1 ?: ""
}

I`m getting

java.lang.StackOverflowError
    at ru.reksoft.okey.models.Address.getAddress1(Address.kt:8)
    at ru.reksoft.okey.models.Address.getAddress1(Address.kt:8)
    //and here are a lot of same lines

So what can I do to make it work properly?

The one solution I see is removing custom getters at all, but what if I really need them?

Upvotes: 0

Views: 1026

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 81929

You should work with the field instead:

class Address {
    var address1: String? = null
        get() = field ?: ""
}

The problem is, that using address1 inside its own setter leads to a recursive call sequence. Instead, the field qualifier refers to the backing field. The recursive sequence leads to the StackOverflowError you encountered.

But actually, you should also think about the sense of your property: It's declared as a nullable String, but you don't allow null since you map it to an empty String. Is "" really accepted for the address? It would be much better to simply do val address1: String = "".

Upvotes: 4

Samuel Robert
Samuel Robert

Reputation: 11032

You are trying to access a property in its getter method. Which will in turn call its getter method and so on... Which mean it's calling itself recursively until the exception.

use field operator to access its value

var address1: String? = null
    get() = field ?: ""

EDIT

Why allow nullability if it doesn't make any sense? Let Kotlin take care of the issue. Just do

var address1: String = ""

Upvotes: 2

Related Questions