What is the difference between JsonElement#getAsString()
vs. JsonElement#toString()
?
Are there situations where one should be used over the
Assuming that you are referring to JsonElement:
getAsString()
convenience method to get this element as a string value.
This method accesses and returns a property of the element, i.e. the value of the element as a java String
object.
toString()
Returns a String representation of this element.
This method is the "standard" java toString method, i.e. returns a human readable representation of the element itself.
For better understanding, let me give you an example:
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());
}
}
Output:
"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)
As you can see, the output is in some cases quite similar (or even equals), but it differs in some other cases. getAsString()
is only defined for primitive types (and arrays containing only a single primitive element) and throws an exception if called e.g. on an object. toString()
will work on all types of JsonElement
.
Now when should you use which method?
toString()
getAsString()