JsonElement#getAsString()vs 之间有什么区别JsonElement#toString()?
是否存在应该使用另一个的情况?
Mar*_*vin 36
假设你指的是JsonElement:
getAsString()
将此元素作为字符串值的便捷方法.
此方法访问并返回元素的属性,即元素的值作为java String对象.
toString()
返回此元素的String表示形式.
此方法是"标准"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());
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
"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)
Run Code Online (Sandbox Code Playgroud)
如您所见,输出在某些情况下非常相似(甚至等于),但在某些其他情况下则不同.getAsString()仅针对基本类型(以及仅包含单个基本元素的数组)定义,并且如果在对象上调用则抛出异常.toString()将适用于所有类型的JsonElement.
现在什么时候应该使用哪种方法?
toString()getAsString()| 归档时间: |
|
| 查看次数: |
20741 次 |
| 最近记录: |