Null values parsing with GSON on Android/Kotlin

Viewed 363

I am trying to parse to/from JSON in an Android/Kotlin app using GSON. When I run this code both foobar and jsonString are null. What am I missing?

    var gson = Gson()

    data class Foobar( val foo: String )

    val foobar = gson.fromJson("""{"foo":"bar"}""",Foobar::class.java)
    val jsonString = gson.toJson(Foobar("bar"))
2 Answers

making use of a basic unit test:

class ExampleUnitTest {

    @Test
    fun fooTest() {

        var gson = Gson()

        data class Foobar( val foo: String )

        val foobar = gson.fromJson("""{"foo":"bar"}""",Foobar::class.java)
        val jsonString = gson.toJson(Foobar("bar"))

        assertEquals(null, foobar)
        assertEquals(null, jsonString)
    }
}

this test fails:

Expected :null<null> 
Actual   :java.lang.String<null>

moving the class outside of the method :

data class Foobar( val foo: String )

@Test
fun fooTest() {

    var gson = Gson()


    val foobar = gson.fromJson("""{"foo":"bar"}""",Foobar::class.java)
    val jsonString = gson.toJson(Foobar("bar"))

    assertEquals(null, foobar)
    assertEquals(null, jsonString)
}

Expected :null
Actual   :Foobar(foo=bar)

as well as

Expected :null
Actual   :{"foo":"bar"}

this is a good thing, this means that we were expecting it to be null, but instead the test failed because our variables actually had values. Your issue is caused by having the data class inside the method, in your case this method is onCreate, moving it out resolves the issue

Since this code is all in the onCreate() method of an Android class (Main Activity), Foobar::class.java didn't take into account the fact that the Foobar class is nested in the MainActivity class. So, this is also a fix:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {

        ...
        
        var gson = Gson()

        data class Foobar( val foo: String )

        val foobar = gson.fromJson(
                     """{"foo":"bar"}""",
                     MainActivity.Foobar::class.java)

        val jsonString = gson.toJson(Foobar("bar"))

        ...
    }
}
Related