GSON JsonElement.getAsString vs. JsonElement.toString?

前端 未结 1 1274
臣服心动
臣服心动 2020-12-15 04:39

What is the difference between JsonElement#getAsString() vs. JsonElement#toString()?

Are there situations where one should be used over the

相关标签:
1条回答
  • 2020-12-15 05:18

    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?

    • If you want to print out debug information, use toString()
    • If you know that you are dealing with a primitive type and you want to display or write the value somewhere, use getAsString()
    • If you don't know the type or if you want to work with the value (i.e. do calculations), use neither. Instead check for the type of the element and use the appropriate method.
    0 讨论(0)
提交回复
热议问题