Class JsonElement

java.lang.Object
com.google.gson.JsonElement
Direct Known Subclasses:
JsonArray, JsonNull, JsonObject, JsonPrimitive

public abstract class JsonElement extends Object
A class representing an element of JSON. It could either be a JsonObject, a JsonArray, a JsonPrimitive or a JsonNull.

This class provides multiple getAs methods which allow

  • obtaining the represented primitive value, for example getAsString()
  • casting to the JsonElement subclasses in a convenient way, for example getAsJsonObject()

Converting JsonElement from / to JSON

There are two ways to parse JSON data as a JsonElement:
  • JsonParser, for example:
     JsonObject jsonObject = JsonParser.parseString("{}").getAsJsonObject();
     
  • Gson.fromJson(..., JsonElement.class)
    It is possible to directly specify a JsonElement subclass, for example:
     JsonObject jsonObject = gson.fromJson("{}", JsonObject.class);
     
To convert a JsonElement to JSON either JsonElement.toString() or the method Gson.toJson(JsonElement) and its overloads can be used.

It is also possible to obtain the TypeAdapter for JsonElement from a Gson instance and then use it for conversion from and to JSON:


 TypeAdapter<JsonElement> adapter = gson.getAdapter(JsonElement.class);

 JsonElement value = adapter.fromJson("{}");
 String json = adapter.toJson(value);
 

JsonElement as JSON data

JsonElement can also be treated as JSON data, allowing to deserialize from a JsonElement and serializing to a JsonElement. The Gson class offers these methods for this: The TypeAdapter class provides corresponding methods as well:
  • Constructor Details

    • JsonElement

      @Deprecated public JsonElement()
      Deprecated.
      Creating custom JsonElement subclasses is highly discouraged and can lead to undefined behavior.
      This constructor is only kept for backward compatibility.
  • Method Details