4

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"
}
Itai Spiegel
  • 151
  • 1
  • 4
  • 10
  • please check: http://stackoverflow.com/questions/5128442/how-to-convert-a-string-to-jsonobject-using-gson-library – kurt_vonnegut Sep 16 '16 at 07:09
  • You can wrap your `String x = "abc"` into a class `StringClass` and use Gson to convert it. – Minh Sep 16 '16 at 07:09

2 Answers2

3

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();
Itai Spiegel
  • 151
  • 1
  • 4
  • 10
2

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"}
Randy
  • 9,419
  • 5
  • 39
  • 56