Giving a string, I’d like to format it as json string with Gson.
What I expect is from "email" to get "{"email" : "$email"}"
I can obviously do
fun serializeUserEmail(email: String): String {
return "{\"email\" : \"$email\"}"
}
and this is what I’m currently doing, and of course I could also create an "Email" class with just one property and use
Gson().toJson(Email())
but none of them are among my expectations. I’d like to do it with just Gson, but not sure it is really possible.
I tried just
Gson().toJson(strEmail)
to no avail. It just returns the same input string, but with double quotes inside, like ""email"".
There is no problem at all with the above function (the one I’m currently using), it’s just that I’m trying to replace everything related to json serialization with Gson.
>Solution :
What I expect is from "email" to get "{"email" : "$email"}"
That is not a JSON string. That is a JSON object. See the JSON documentation, or Wikipedia, or any number of other resources on the JSON data format.
It just returns the same input string, but with double quotes inside, like ""email"".
If strEmail is "email", then that is the correct output. ""email"" is a JSON string representation of "email".
it’s just that I’m trying to replace everything related to json serialization with Gson
Then you already have your solution:
I could also create an "Email" class with just one property and use
Gson().toJson(Email())
Note that Gson is no longer being actively maintained outside of bug fixes. Most of the original Gson developers are now contributing to Moshi, as I understand it.