一、使用区别
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)
二、源码分析
toString源码
/**
* Returns a String representation of this element.
*/
@Override
public String toString() {
try {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setLenient(true);
Streams.write(this, jsonWriter);
return stringWriter.toString();
} catch (IOException e) {
throw new AssertionError(e);
}
}
getAsString源码
/**
* convenience method to get this element as a string value.
*
* @return get this element as a string value.
* @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
* string value.
* @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
* more than a single element.
*/
public String getAsString() {
throw new UnsupportedOperationException(getClass().getSimpleName());
}
由上述可知:
- toString()返回的是JsonElement的字符串,所有是带双引号的,eg: “foo”;getAsString()返回的是JsonElement的字符串值,所以不带双引号,eg:foot
- getAsString的入参不是以下类型:JsonPrimitive类型、String类型或者只包含单个元素的JsonArray类型,就会抛出异常;