Android. Cannot parse json string from bundle

46 Views Asked by At

I'm trying to parse json string from bundle to object. But I get error:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $

Here is my code:

val jsonString = bundle.getString(key)
val type = Info::class.java
val json = Gson().fromJson(jsonString, type)

My Info data class:

data class Info(
   val id: Long,
   val canProceed: Boolean,
   val wasAdded: Boolean,
)

I tried to evaluate the expression and I see that bundle.getString(key) returns

"{\"id\":6067857,\"canProceed\":false,\"wasAdded\":false}"

Everything looks good, but for some reason I'm getting the error I described above. Moreover, if in the expression evaluation mode I copy the return value from the bundle.getString(key) and manually substitute it, as here:

Gson().fromJson("{\"id\":6067857,\"canProceed\":false,\"wasAdded\":false}", type)

then everything works well, I get the object. What could be the problem ?

Please help me.

P.S. What I pass to my bundle:

val info: Info = Info(id = 6067857, canProceed = false, wasAdded = false) 
bundle.putString(key, Gson().toJson(info))
1

There are 1 best solutions below

0
tomerpacific On

The error message you are receiving indicates that Expected BEGIN_OBJECT but was STRING at line 1, which means that Gson is expecting your JSON string to being with an object bracket { and not with an open quotes ".

What you have shared also shows you have a JSON string.

bundle.getString(key) returns a JSON string and as evidenced by what you wrote works properly.

If you write the code below, it should work:

val json = Gson().fromJson(bundle.getString(key), Info::class.java)