All Implemented Interfaces:
Serializable, Cloneable, Map<String,Object>
Direct Known Subclasses:
DelegateMap

public class JsonMap extends MarshalledMap
Java implementation of a JSON object.

This class is a subclass of MarshalledMap that carries strict-JSON-specific surface, including strict-JSON toString() (via Json.of(Object)), JsonParser-defaulting CharSequence / Reader constructors, and convenience methods for serializing to the various JSON dialects (JSON5, JSON Lines, canonical JSON, HJSON).

v10.0 behavioral break: toString() now produces strict (RFC 8259) JSON (was JSON5), and the CharSequence / Reader constructors now default to JsonParser.DEFAULT (was Json5Parser.DEFAULT). For the previous JSON5 behavior use Json5Map.

Note that the use of this class is optional for generating JSON. The serializers will accept any objects that implement the Map interface. But this class provides some useful additional functionality when working with JSON models constructed from Java Collections Framework objects. For example, a constructor is provided for converting a JSON object string directly into a Map. It also contains accessor methods for to avoid common typecasting when accessing elements in a list.

Example:

// Construct an empty Map JsonMap map = JsonMap.of(); // Construct a Map from JSON map = JsonMap.ofString("{a:'A',b:{c:'C',d:123}}"); // Construct a Map using the append method map = JsonMap.of().a("foo","x").a("bar",123).a("baz",true); // Construct a Map from XML generated by XmlSerializer String xml = "<object><a type='string'>A</a><b type='object'><c type='string'>C</c><d type='number'>123</d></b></object>"; map = JsonMap.of(xml, XmlParser.DEFAULT); // Construct a Map from a URL GET parameter string generated by UrlEncodingParser String urlParams = "?a='A'&b={c:'C',d:123}"; map = JsonMap.of(urlParams, UrlEncodingParser.DEFAULT); // Construct JSON from JsonMap map = JsonMap.ofString("{foo:'bar'},{baz:[123,true]}"); String json = map.toString(); // Produces "{foo:'bar'},{baz:[123,true]}" json = map.toString(JsonSerializer.DEFAULT); // Equivalent json = JsonSerializer.DEFAULT.write(map); // Equivalent // Get a map entry as an Integer map = JsonMap.ofString("{foo:123}"); Integer integer = map.getInt("foo"); integer = map.get(Integer.class, "foo"); // Equivalent // Add an inner map JsonMap map1 = JsonMap.ofString("{a:1}"); JsonMap map2 = JsonMap.ofString("{b:2}").setInner(map1); int _int = map2.getInt("a"); // a == 1

Notes:
  • This class is not thread safe.
See Also:
  • Field Details

  • Constructor Details

    • JsonMap

      public JsonMap()
      Construct an empty map.
    • JsonMap

      public JsonMap(MarshallingSession session)
      Construct an empty map with the specified bean context.
      Parameters:
      session - The bean session to use for creating beans.
    • JsonMap

      public JsonMap(CharSequence json) throws ParseException
      Construct a map initialized with the specified JSON.
      Parameters:
      json - The JSON text to parse.
      Must be strict (RFC 8259) JSON; for JSON5 input use Json5Map or pass Json5Parser.DEFAULT explicitly.
      Throws:
      ParseException - Malformed input encountered.
    • JsonMap

      public JsonMap(CharSequence in, Parser p) throws ParseException
      Construct a map initialized with the specified string.
      Parameters:
      in - The input being parsed.
      Can be null or empty (results in an empty map; no parsing occurs).
      p - The parser to use to parse the input.
      If null, uses JsonParser.
      Throws:
      ParseException - Malformed input encountered.
    • JsonMap

      public JsonMap(Map<?,?> in)
      Construct a map initialized with the specified map.
      Parameters:
      in - The map to copy.
      Can be null (results in an empty map).
      Keys will be converted to strings using Object.toString().
    • JsonMap

      public JsonMap(Object... keyValuePairs)
      Construct a map initialized with the specified key/value pairs.
      Examples:

      JsonMap map = new JsonMap("key1","val1","key2","val2");

      Parameters:
      keyValuePairs - A list of key/value pairs to add to this map.
    • JsonMap

      public JsonMap(Reader json) throws ParseException
      Construct a map initialized with the specified reader containing JSON.
      Parameters:
      json - The reader containing JSON text to parse.
      Must be strict (RFC 8259) JSON; for JSON5 input use Json5Map or pass Json5Parser.DEFAULT explicitly.
      Throws:
      ParseException - Malformed input encountered.
    • JsonMap

      public JsonMap(Reader in, Parser p) throws ParseException
      Construct a map initialized with the specified string.
      Parameters:
      in - The reader containing the input being parsed.
      Must be strict (RFC 8259) JSON.
      p - The parser to use to parse the input.
      If null, uses JsonParser.
      Throws:
      ParseException - Malformed input encountered.
  • Method Details

    • create

      public static JsonMap create()
      Construct an empty map.
      Returns:
      An empty map.
    • filteredMap

      public static JsonMap filteredMap()
      Construct an empty filtered map.
      Returns:
      An empty map.
    • filteredMap

      public static JsonMap filteredMap(Object... keyValuePairs)
      Construct a filtered map initialized with the specified key/value pairs.

      Same as of(Object...) but calls filtered() on the created map.

      Parameters:
      keyValuePairs - A list of key/value pairs to add to this map.
      Returns:
      A new map, never null.
    • of

      public static JsonMap of(Map<?,?> values)
      Construct a map initialized with the specified map.
      Parameters:
      values - The map to copy.
      Can be null (returns null).
      Keys will be converted to strings using Object.toString().
      Returns:
      A new map or null if the map was null.
    • of

      public static JsonMap of(Object... keyValuePairs)
      Construct a map initialized with the specified key/value pairs.
      Examples:

      JsonMap map = new JsonMap("key1","val1","key2","val2");

      Parameters:
      keyValuePairs - A list of key/value pairs to add to this map.
      Returns:
      A new map, never null.
    • ofString

      public static JsonMap ofString(CharSequence json) throws ParseException
      Construct a map initialized with the specified JSON string.
      Parameters:
      json - The JSON text to parse.
      Can be normal or simplified JSON.
      Returns:
      A new map (empty if the input was null), never null.
      Throws:
      ParseException - Malformed input encountered.
    • ofString

      public static JsonMap ofString(Reader json) throws ParseException
      Construct a map initialized with the specified reader containing JSON.
      Parameters:
      json - The reader containing JSON text to parse.
      Can contain normal or simplified JSON.
      Returns:
      A new map (empty if the input was null), never null.
      Throws:
      ParseException - Malformed input encountered.
    • ofString

      public static JsonMap ofString(CharSequence in, Parser p) throws ParseException
      Construct a map initialized with the specified string.
      Parameters:
      in - The input being parsed.
      p - The parser to use to parse the input.
      If null, uses JsonParser.
      Returns:
      A new map (empty if the input was null), never null.
      Throws:
      ParseException - Malformed input encountered.
    • ofString

      public static JsonMap ofString(Reader in, Parser p) throws ParseException
      Construct a map initialized with the specified string.
      Parameters:
      in - The reader containing the input being parsed.
      Can contain normal or simplified JSON.
      p - The parser to use to parse the input.
      If null, uses JsonParser.
      Returns:
      A new map (empty if the input was null), never null.
      Throws:
      ParseException - Malformed input encountered.
    • append

      public JsonMap append(Map<String,Object> values)
      Description copied from class: MarshalledMap
      Appends all the entries in the specified map to this map.
      Overrides:
      append in class MarshalledMap
      Parameters:
      values - The map to copy. Can be null (no-op).
      Returns:
      This object.
    • append

      public JsonMap append(String key, Object value)
      Description copied from class: MarshalledMap
      Adds an entry to this map.
      Overrides:
      append in class MarshalledMap
      Parameters:
      key - The key.
      value - The value.
      Returns:
      This object.
    • appendFirst

      public <T> JsonMap appendFirst(Predicate<T> test, String key, T... values)
      Description copied from class: MarshalledMap
      Adds the first value that matches the specified predicate.
      Overrides:
      appendFirst in class MarshalledMap
      Type Parameters:
      T - The value types.
      Parameters:
      test - The predicate to match against.
      key - The key.
      values - The values to test.
      Returns:
      This object.
    • appendIf

      public JsonMap appendIf(boolean flag, String key, Object value)
      Description copied from class: MarshalledMap
      Add if flag is true.
      Overrides:
      appendIf in class MarshalledMap
      Parameters:
      flag - The flag to check.
      key - The key.
      value - The value.
      Returns:
      This object.
    • appendIf

      public <T> JsonMap appendIf(Predicate<T> test, String key, T value)
      Description copied from class: MarshalledMap
      Add if predicate matches value.
      Overrides:
      appendIf in class MarshalledMap
      Type Parameters:
      T - The value type.
      Parameters:
      test - The predicate to match against.
      key - The key.
      value - The value.
      Returns:
      This object.
    • appendIfAbsent

      public JsonMap appendIfAbsent(String key, Object value)
      Description copied from class: MarshalledMap
      Adds a value in this map if the entry does not exist or the current value is null.
      Overrides:
      appendIfAbsent in class MarshalledMap
      Parameters:
      key - The map key.
      value - The value to set if the current value does not exist or is null.
      Returns:
      This object.
    • appendIfAbsentIf

      public <T> JsonMap appendIfAbsentIf(Predicate<T> predicate, String key, T value)
      Description copied from class: MarshalledMap
      Adds a value in this map if the entry does not exist or the current value is null and the value matches the specified predicate.
      Overrides:
      appendIfAbsentIf in class MarshalledMap
      Type Parameters:
      T - The value type.
      Parameters:
      predicate - The predicate to test the value with.
      key - The map key.
      value - The value to set if the current value does not exist or is null.
      Returns:
      This object.
    • toJson

      public String toJson()
      Serializes this map to a standard JSON string.
      Returns:
      This object as a standard JSON string.
    • toJson5

      public String toJson5()
      Serializes this map to a JSON5 string.

      A synonym for toString().

      Returns:
      This object as a JSON5 string.
    • toJsonl

      public String toJsonl()
      Serializes this map to a JSON Lines string.
      Returns:
      This object as a JSON Lines string.
    • toJcs

      public String toJcs()
      Serializes this map to a canonical JSON string (RFC 8785).
      Returns:
      This object as a canonical JSON string.
    • toHjson

      public String toHjson()
      Serializes this map to an HJSON string.
      Returns:
      This object as an HJSON string.
    • toReadableJson5

      Serializes this map to a readable (indented) JSON5 string using Json5Serializer.DEFAULT_READABLE.
      Returns:
      This object serialized as a readable JSON5 string.
    • exclude

      public JsonMap exclude(String... keys)
      Description copied from class: MarshalledMap
      Returns a copy of this map without the specified keys.
      Overrides:
      exclude in class MarshalledMap
      Parameters:
      keys - The keys of the entries not to copy.
      Returns:
      A new map without the keys and values from this map.
    • filtered

      public JsonMap filtered()
      Description copied from class: MarshalledMap
      Enables filtering based on default values.

      Any of the following types will be ignored when set as values in this map:

      • null
      • false
      • -1 (any Number type)
      • Empty arrays/collections/maps.
      Overrides:
      filtered in class MarshalledMap
      Returns:
      This object.
    • filtered

      public JsonMap filtered(Predicate<Object> value)
      Description copied from class: MarshalledMap
      Enables filtering based on a predicate test.

      If the predicate evaluates to false on values added to this map, the entry will be skipped.

      Overrides:
      filtered in class MarshalledMap
      Parameters:
      value - The value tester predicate.
      Returns:
      This object.
    • findList

      public JsonList findList(String... keys)
      Description copied from class: MarshalledMap
      Returns the first entry that exists converted to a MarshalledList.
      Overrides:
      findList in class MarshalledMap
      Parameters:
      keys - The list of keys to look for.
      Returns:
      The converted value of the first key in the list that has an entry in this map, or null if the map contains no mapping for any of the keys.
    • findMap

      public JsonMap findMap(String... keys)
      Description copied from class: MarshalledMap
      Returns the first entry that exists converted to a MarshalledMap.
      Overrides:
      findMap in class MarshalledMap
      Parameters:
      keys - The list of keys to look for.
      Returns:
      The converted value of the first key in the list that has an entry in this map, or null if the map contains no mapping for any of the keys.
    • getList

      public JsonList getList(String key)
      Description copied from class: MarshalledMap
      Returns the specified entry value converted to a MarshalledList.
      Overrides:
      getList in class MarshalledMap
      Parameters:
      key - The key.
      Returns:
      The converted value, or null if the map contains no mapping for this key.
    • getList

      public JsonList getList(String key, boolean createIfNotExists)
      Description copied from class: MarshalledMap
      Same as MarshalledMap.getList(String) but creates a new empty MarshalledList if it doesn't already exist.
      Overrides:
      getList in class MarshalledMap
      Parameters:
      key - The key.
      createIfNotExists - If mapping doesn't already exist, create one with an empty MarshalledList.
      Returns:
      The converted value, or an empty value if the map contains no mapping for this key.
    • getList

      public JsonList getList(String key, JsonList defVal)
      Returns the specified entry value converted to a JsonList.
      Parameters:
      key - The key.
      defVal - The default value if the map doesn't contain the specified mapping.
      Returns:
      The converted value, or the default value if the map contains no mapping for this key.
      Throws:
      InvalidDataConversionException - If value cannot be converted.
    • getMap

      public JsonMap getMap(String key)
      Description copied from class: MarshalledMap
      Returns the specified entry value converted to a Map.
      Overrides:
      getMap in class MarshalledMap
      Parameters:
      key - The key.
      Returns:
      The converted value, or null if the map contains no mapping for this key.
    • getMap

      public JsonMap getMap(String key, boolean createIfNotExists)
      Description copied from class: MarshalledMap
      Same as MarshalledMap.getMap(String) but creates a new empty MarshalledMap if it doesn't already exist.
      Overrides:
      getMap in class MarshalledMap
      Parameters:
      key - The key.
      createIfNotExists - If mapping doesn't already exist, create one with an empty MarshalledMap.
      Returns:
      The converted value, or an empty value if the map contains no mapping for this key.
    • getMap

      public JsonMap getMap(String key, JsonMap defVal)
      Returns the specified entry value converted to a JsonMap.
      Parameters:
      key - The key.
      defVal - The default value if the map doesn't contain the specified mapping.
      Returns:
      The converted value, or the default value if the map contains no mapping for this key.
      Throws:
      InvalidDataConversionException - If value cannot be converted.
    • include

      public JsonMap include(String... keys)
      Description copied from class: MarshalledMap
      Returns a copy of this map with only the specified keys.
      Overrides:
      include in class MarshalledMap
      Parameters:
      keys - The keys of the entries to copy.
      Returns:
      A new map with just the keys and values from this map.
    • inner

      public JsonMap inner(Map<String,Object> inner)
      Description copied from class: MarshalledMap
      Set an inner map in this map to allow for chained get calls.

      If MarshalledMap.get(Object) returns null, then MarshalledMap.get(Object) will be called on the inner map.

      Overrides:
      inner in class MarshalledMap
      Parameters:
      inner - The inner map. Can be null to remove the inner map from an existing map.
      Returns:
      This object.
    • keepAll

      public JsonMap keepAll(String... keys)
      Description copied from class: MarshalledMap
      The opposite of MarshalledMap.removeAll(String...).

      Discards all keys from this map that aren't in the specified list.

      Overrides:
      keepAll in class MarshalledMap
      Parameters:
      keys - The keys to keep.
      Returns:
      This map.
    • modifiable

      public JsonMap modifiable()
      Description copied from class: MarshalledMap
      Returns a modifiable copy of this map if it's unmodifiable.
      Overrides:
      modifiable in class MarshalledMap
      Returns:
      A modifiable copy of this map if it's unmodifiable, or this map if it is already modifiable.
    • newMarshalledMap

      Description copied from class: MarshalledMap
      Factory hook used by MarshalledMap.cast(Class) / MarshalledMap.cast(ClassMeta) when the target map type cannot be instantiated directly (e.g. when the caller asks for the Map interface).

      Subclasses should override to return an instance of the matching XMap variant so that callers chaining off of cast(Map.class) still see their flavored map type.

      Overrides:
      newMarshalledMap in class MarshalledMap
      Parameters:
      bs - The marshalling session to associate with the new map.
      Returns:
      A new map instance.
    • putJson

      public void putJson(String key, String json) throws ParseException
      Convenience method for inserting JSON directly into an attribute on this object.

      The JSON text can be an object (i.e. "{...}") or an array (i.e. "[...]").

      Input must be strict (RFC 8259) JSON; for JSON5 use Json5Map.putJson5(String,String).

      Parameters:
      key - The key.
      json - The JSON text that will be parsed into an Object and then inserted into this map.
      Throws:
      ParseException - Malformed input encountered.
    • session

      Description copied from class: MarshalledMap
      Override the default bean session used for converting POJOs.

      Default is MarshallingContext.DEFAULT, which is sufficient in most cases.

      Useful if you're serializing/parsing beans with transforms defined.

      Overrides:
      session in class MarshalledMap
      Parameters:
      session - The new bean session.
      Returns:
      This object.
    • setBeanSession

      Description copied from class: MarshalledMap
      Sets the MarshallingSession currently associated with this map.
      Overrides:
      setBeanSession in class MarshalledMap
      Parameters:
      value - The MarshallingSession currently associated with this map.
      Returns:
      This object.
    • toString

      public String toString()
      Overrides:
      toString in class AbstractMap<String,Object>
    • unmodifiable

      Description copied from class: MarshalledMap
      Returns an unmodifiable copy of this map if it's modifiable.
      Overrides:
      unmodifiable in class MarshalledMap
      Returns:
      An unmodifiable copy of this map if it's modifiable, or this map if it is already unmodifiable.
    • writeTo

      Convenience method for serializing this map to the specified Writer using the Json.DEFAULT marshaller.
      Parameters:
      w - The writer to serialize this object to.
      Returns:
      This object.
      Throws:
      IOException - If a problem occurred trying to write to the writer.
      SerializeException - If a problem occurred trying to convert the output.