Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Android Kotlin: Serialize string to json string with Gson

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading