Home Ask Login Register

Developers Planet

Your answer is one click away!

xpg94 February 2016

GSON does not return JSON key

I am using GSON to convert objects into JSON. I have this:

String name = "MyName";

and I use the following statement to convert it to json:

print(new Gson().toJson(name));

and the output is : "MyName" How can I make it print in this way:



Balaji Krishnan February 2016

public class Test {
    String name = "myName";
    public static void main(String[] args) {
        System.out.println(new Gson().toJson(new Test()));

andrucz February 2016

There are two options:

class YourClass {
    private String name;

    // getters and setters...

YourClass object = new YourClass();
print(new Gson().toJson(object));

And using JsonObject:

JsonObject object = new JsonObject();
object.addProperty("name", "MyName");
print(new Gson().toJson(object);

Post Status

Asked in February 2016
Viewed 2,434 times
Voted 10
Answered 2 times


Leave an answer

Quote of the day: live life