JSON string from Gson: remove double quotes

It's not documented properly, but JsonElement#toString() gets you a string that represents the JSON element and would be appropriate for re-creating the JSON serialization. What you want is JsonElement#getAsString(). This will throw an error if you're not looking at a string, but if you are, you'll get the string value.

Here's a test program to demonstrate:

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class Test {
    public static void main(String[] args) {
        String in = "{\"hello\":\"world\"}";
        System.out.println(in);
        JsonElement root = new JsonParser().parse(in);
        System.out.println(root.getAsJsonObject().get("hello").toString());
        System.out.println(root.getAsJsonObject().get("hello").getAsString());
    }
}

And its output:

{"hello":"world"}
"world"
world

Tags:

Java

Json

Gson