JsonElement#getAsString()
有什么区别对比 JsonElement#toString()
?
在某些情况下,应该使用一种方法吗?
请您参考如下方法:
假设您指的是 JsonElement
:getAsString()
convenience method to get this element as a string value.
此方法访问并返回元素的属性,即元素的值作为 java
String
目的。
toString()
Returns a String representation of this element.
这种方法是“标准”java
toString
方法,即返回元素本身的人类可读表示。
为了更好的理解,我举个例子:
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public class GsonTest {
public static void main(String[] args) {
JsonElement jsonElement = new JsonPrimitive("foo");
System.out.println(jsonElement.toString());
System.out.println(jsonElement.getAsString());
jsonElement = new JsonPrimitive(42);
System.out.println(jsonElement.toString());
System.out.println(jsonElement.getAsString());
jsonElement = new JsonPrimitive(true);
System.out.println(jsonElement.toString());
System.out.println(jsonElement.getAsString());
jsonElement = new JsonObject();
((JsonObject) jsonElement).addProperty("foo", "bar");
((JsonObject) jsonElement).addProperty("foo2", 42);
System.out.println(jsonElement.toString());
System.out.println(jsonElement.getAsString());
}
}
输出:
"foo"
foo
42
42
true
true
{"foo":"bar","foo2":42}
Exception in thread "main" java.lang.UnsupportedOperationException: JsonObject
at com.google.gson.JsonElement.getAsString(JsonElement.java:185)
如您所见,输出在某些情况下非常相似(甚至相等),但在其他一些情况下则不同。
getAsString()
仅针对基本类型(以及仅包含单个基本元素的数组)定义,如果调用则抛出异常,例如在一个物体上。
toString()
将适用于所有类型的
JsonElement
.
现在应该什么时候使用哪种方法?
toString()
getAsString()