我是 java 新手,我正在尝试使用 name
和 value
创建一个 json 字符串。
public static String serializeToken(String name,String value){
JsonObject json = new JsonObject();
json.addProperty(name, value);
return json.getAsString();
}
但是对 getAsString
的调用会引发异常,消息只是:
JsonObject
最佳答案
Here's getAsString
方法的文档如下:
convenience method to get this element as a string value.
Throws:
ClassCastException - if the element is of not a JsonPrimitive and is not a valid string value. IllegalStateException - if the element is of the type JsonArray but contains more than a single element.
因此,如果该元素不是 Primitive(在本例中它不是),它将抛出 Exception
。如果你想打印 json
字符串,那么你需要调用 toString
方法,例如:
JsonObject json = new JsonObject();
json.addProperty("test", "value");
String jsonString = json.toString();
System.out.println(jsonString);
关于java - JsonObject getAsString 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45465302/