它的文档记录不正确,但是
JsonElement#toString()会为您提供一个表示JSON元素的字符串,并且适合于重新创建JSON序列化。你想要的是
JsonElement#getAsString()。如果您不查看字符串,这将引发错误,但是如果您查看字符串,则将获得字符串值。
这是一个演示程序:
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()); }}及其输出:
{"hello":"world"}"world"world


