Itai Spiegel
Itai Spiegel

Reputation: 151

Using Gson to convert a string object to JSON string in Java

Let's say we have the following string:

String x = "abc";

My question is how would I use the Gson library to convert the given string, to the following JSON string:

{
   x : "abc"
}

Upvotes: 4

Views: 6446

Answers (2)

Randy
Randy

Reputation: 9849

http://www.studytrails.com/java/json/java-google-json-parse-json-to-java.jsp

class Albums {
    public String x;
}

Lets convert this to JSON and see how it looks

import com.google.gson.Gson;

public class JavaToJsonAndBack {
    public static void main(String[] args) {
        Albums albums = new Albums();
        albums.x= "abc";

        Gson gson = new Gson();

        System.out.println(gson.toJson(albums));
    }
}

This is how the resulting JSON looks like

{"x":"abc"}

Upvotes: 2

Itai Spiegel
Itai Spiegel

Reputation: 151

Of course I could have created a new class that wraps the string object, and convert it to a JSON string, but it didn't seem necessary. Anyway, the solution I found was this:

JsonObject x = new JsonObject();
x.addProperty("x", "abc");

String json = x.toString();

Upvotes: 3

Related Questions