Class JsonElement

java.lang.Object
name.martingeisse.grumpyjson.json_model.JsonElement
Direct Known Subclasses:
JsonArray, JsonBoolean, JsonNull, JsonNumber, JsonObject, JsonString

public abstract class JsonElement extends Object
Base class for all JSON elements.

Code that wants to build a JSON structure, such as a serializer, should use the .of() factory methods in the subclasses of this class to create JSON nodes.

Code that wants to analyze a JSON structure, such as a deserializer, has two options:
  • If only a single kind of JSON node is valid for the value to be deserialized, use one of the deserializerExpectsXXX methods to check for the correct type of node, throw an exception if another kind of node is present, and obtain the values from that node.
  • If multiple kinds of JSON nodes are valid for the value to be serialized, use instanceof with pattern matching like this: if (myJsonElement instanceof JsonString s) {...s.getValue()...}

This class and all its subclasses are immutable. They do not share lists and maps with that they are constructed from, and all lists and maps they return are immutable. To guarantee immutability, these classes do make one assumption: The Numbers from which JsonNumbers get constructed must be immutable too -- unfortunately, Java does not guarantee that on its own, and mutable implementations exist.

Note: This class does not use the term "primitive", and in particular does not provide a method such as isPrimitive(), to avoid confusion because different JSON libraries disagree on whether null is a primitive.

Implementations support equals() / hashCode() / toString(), although without regard to performance. While all these methods are rarely needed for JSON processing, they are useful in unit tests. The toString() method is intentionally written in such a way that the output is NOT valid JSON, so it is not accidentally used to generate JSON -- doing so would be slow and likely handle some edge cases inccorrectly.