Skip to main content
 首页 » 编程设计

GSON JsonElement.getAsString 与 JsonElement.toString

2025年02月15日20bluestorm

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()
  • 如果您不知道类型或者您想使用该值(即进行计算),请不要使用它们。而是检查元素的类型并使用适当的方法。