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"
}
2
  • please check: stackoverflow.com/questions/5128442/… Commented Sep 16, 2016 at 7:09
  • You can wrap your String x = "abc" into a class StringClass and use Gson to convert it. Commented Sep 16, 2016 at 7:09

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.