Class JsonUtils

java.lang.Object
net.solarnetwork.codec.JsonUtils

public final class JsonUtils extends Object
Utilities for JSON data.

The ObjectMapper used internally by this class supports:

  • java.time date/time values, serialized as strings using the RFC 3339 profile of ISO-8601 with a space separator between date/time sections instead of a T character.
  • null values are not serialized.
  • Floating point numbers are deserialized as BigDecimal instances.
Since:
1.72
Version:
2.1
Author:
matt
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final com.fasterxml.jackson.databind.Module
    A module for handling datum objects.
    static final com.fasterxml.jackson.databind.Module
    A module for handling Java date and time objects in The SolarNetwork Way.
    static final com.fasterxml.jackson.databind.Module
    A module for handling Java date and time objects in The SolarNetwork Way but instant values serialized as epoch number values instead of formatted strings.
    static final com.fasterxml.jackson.core.type.TypeReference<LinkedHashMap<String,Object>>
    A type reference for a Map with string keys.
  • Method Summary

    Modifier and Type
    Method
    Description
    static final com.fasterxml.jackson.databind.ObjectMapper
    createObjectMapper(com.fasterxml.jackson.core.JsonFactory jsonFactory, com.fasterxml.jackson.databind.Module... modules)
    Create an ObjectMapper instance with optional modules.
    static String
    getJSONString(Object o, String defaultValue)
    Convert an object to a JSON string.
    static <T> T
    getObjectFromJSON(String json, Class<T> clazz)
    Convert a JSON string to an object.
    static Map<String,Object>
    Convert a JSON string to a Map with string keys.
    static Map<String,Object>
    Convert an object into a Map with string keys.
    static Map<String,Object>
    getStringMapFromTree(com.fasterxml.jackson.databind.JsonNode node)
    Convert a JSON tree object to a Map with string keys.
    static com.fasterxml.jackson.databind.JsonNode
    Convert an object into a JSON tree.
    static Instant
    Parse an ISO 8601 timestamp value into an Instant.
    static com.fasterxml.jackson.databind.ObjectMapper
    Create a new ObjectMapper based on the default internal configuration used by other methods in this class.
    static com.fasterxml.jackson.databind.ObjectMapper
    newDatumObjectMapper(com.fasterxml.jackson.core.JsonFactory jsonFactory)
    Create a new ObjectMapper based on the internal configuration used by other methods in this class.
    static com.fasterxml.jackson.databind.ObjectMapper
    Create a new ObjectMapper based on the default internal configuration used by other methods in this class.
    static com.fasterxml.jackson.databind.ObjectMapper
    newObjectMapper(com.fasterxml.jackson.core.JsonFactory jsonFactory)
    Create a new ObjectMapper based on the internal configuration used by other methods in this class.
    static BigDecimal
    parseBigDecimalAttribute(com.fasterxml.jackson.databind.JsonNode node, String key)
    Parse a BigDecimal from a JSON object attribute value.
    static <T> T
    parseDateAttribute(com.fasterxml.jackson.core.TreeNode node, String key, DateTimeFormatter dateFormat, TemporalQuery<T> query)
    Parse a date from a JSON object attribute value.
    static BigDecimal
    parseDecimal(com.fasterxml.jackson.core.JsonParser p)
    Parse a JSON numeric value into a BigDecimal.
    static BigDecimal[]
    parseDecimalArray(com.fasterxml.jackson.core.JsonParser p)
    Parse a JSON array of numeric values into a BigDecimal array.
    static void
    parseIndexedFieldsObject(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.databind.DeserializationContext ctxt, Object[] data, Map<String,? extends IndexedField> fields)
    Parse a JSON object using a map of IndexedField values.
    static Integer
    parseIntegerAttribute(com.fasterxml.jackson.databind.JsonNode node, String key)
    Parse a Integer from a JSON object attribute value.
    static Long
    parseLongAttribute(com.fasterxml.jackson.databind.JsonNode node, String key)
    Parse a Long from a JSON object attribute value.
    static Map<String,?>
    parseSimpleMap(com.fasterxml.jackson.core.JsonParser p)
    Parse a simple Map from a JSON object.
    static String[]
    parseStringArray(com.fasterxml.jackson.core.JsonParser p)
    Parse a JSON array of scalar values into a string array.
    static String
    parseStringAttribute(com.fasterxml.jackson.databind.JsonNode node, String key)
    Parse a String from a JSON object attribute value.
    static void
    writeBitmaskValue(com.fasterxml.jackson.core.JsonGenerator gen, String fieldName, Set<? extends Bitmaskable> value)
    Write a bitmask set as a field number value.
    static void
    writeDecimalArray(com.fasterxml.jackson.core.JsonGenerator generator, BigDecimal[] array)
    Write a string array as a JSON array of numbers.
    static void
    writeDecimalArrayValues(com.fasterxml.jackson.core.JsonGenerator generator, BigDecimal[] array, int count)
    Write a fixed number of decimal array values as JSON array numbers.
    static void
    writeIso8601Timestamp(com.fasterxml.jackson.core.JsonGenerator gen, String fieldName, Instant value)
    Write a timestamp field value in ISO 8601 form.
    static void
    writeMetadata(com.fasterxml.jackson.core.JsonGenerator generator, GeneralDatumMetadata meta)
    Write metadata to a JSON generator.
    static void
    writeNumberField(com.fasterxml.jackson.core.JsonGenerator gen, String fieldName, Number value)
    Write a number field value using the smallest possible number type.
    static void
    writeSimpleMap(com.fasterxml.jackson.core.JsonGenerator generator, Map<String,?> value)
    Write a simple Map as a JSON object.
    static void
    writeStringArray(com.fasterxml.jackson.core.JsonGenerator generator, String[] array)
    Write a string array as a JSON array of strings.
    static void
    writeStringArrayField(com.fasterxml.jackson.core.JsonGenerator generator, String fieldName, String[] array)
    Write a string array as a JSON object field that is an array of strings.
    static void
    writeStringArrayValues(com.fasterxml.jackson.core.JsonGenerator generator, String[] array, int count)
    Write a fixed number of string array values as JSON array numbers.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • STRING_MAP_TYPE

      public static final com.fasterxml.jackson.core.type.TypeReference<LinkedHashMap<String,Object>> STRING_MAP_TYPE
      A type reference for a Map with string keys.
    • JAVA_TIME_MODULE

      public static final com.fasterxml.jackson.databind.Module JAVA_TIME_MODULE
      A module for handling Java date and time objects in The SolarNetwork Way.

      This field will be null if the com.fasterxml.jackson.datatype.jsr310.JavaTimeModule class is not available.

      Since:
      2.0
    • JAVA_TIMESTAMP_MODULE

      public static final com.fasterxml.jackson.databind.Module JAVA_TIMESTAMP_MODULE
      A module for handling Java date and time objects in The SolarNetwork Way but instant values serialized as epoch number values instead of formatted strings.

      Note for this module to work as expected, the associated ObjectMapper should have the SerializationFeature.WRITE_DATES_AS_TIMESTAMPS enabled. Also consider the SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS and DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS features (the default ObjectMapper used internally by this class disable both those).

      This field will be null if the com.fasterxml.jackson.datatype.jsr310.JavaTimeModule class is not available.

      Since:
      2.0
    • DATUM_MODULE

      public static final com.fasterxml.jackson.databind.Module DATUM_MODULE
      A module for handling datum objects.
      Since:
      2.0
  • Method Details

    • createObjectMapper

      public static final com.fasterxml.jackson.databind.ObjectMapper createObjectMapper(com.fasterxml.jackson.core.JsonFactory jsonFactory, com.fasterxml.jackson.databind.Module... modules)
      Create an ObjectMapper instance with optional modules.
      Parameters:
      jsonFactory - an optional factory to use
      modules - optional modules to register; can be completely omitted and individual elements are allowed to be null (e.g. optionally missing modules)
      Returns:
      the new mapper
      Throws:
      RuntimeException - if there is any problem creating the mapper
      Since:
      2.0
    • getJSONString

      public static String getJSONString(Object o, String defaultValue)
      Convert an object to a JSON string.

      This is designed for simple values. An internal ObjectMapper will be used, and null values will not be included in the output. All exceptions while serializing the object are caught and ignored.

      Parameters:
      o - the object to serialize to JSON
      defaultValue - a default value to use if o is null or if any error occurs serializing the object to JSON
      Returns:
      the JSON string
    • getObjectFromJSON

      public static <T> T getObjectFromJSON(String json, Class<T> clazz)
      Convert a JSON string to an object.

      This is designed for simple values. An internal ObjectMapper will be used, and all floating point values will be converted to BigDecimal values to faithfully represent the data. All exceptions while deserializing the object are caught and ignored.

      Type Parameters:
      T - the desired object type
      Parameters:
      json - the JSON string to convert
      clazz - the type of Object to map the JSON into
      Returns:
      the object
      Since:
      1.1
    • getStringMap

      public static Map<String,Object> getStringMap(String json)
      Convert a JSON string to a Map with string keys.

      This is designed for simple values. An internal ObjectMapper will be used, and all floating point values will be converted to BigDecimal values to faithfully represent the data. All exceptions while deserializing the object are caught and ignored.

      Parameters:
      json - the JSON to convert
      Returns:
      the map, or null if json is null or empty, or any exception occurs generating the JSON
    • getStringMapFromTree

      public static Map<String,Object> getStringMapFromTree(com.fasterxml.jackson.databind.JsonNode node)
      Convert a JSON tree object to a Map with string keys.

      This is designed for simple values. An internal ObjectMapper will be used, and all floating point values will be converted to BigDecimal values to faithfully represent the data. All exceptions while deserializing the object are caught and ignored.

      Parameters:
      node - the JSON object to convert
      Returns:
      the map, or null if node is not a JSON object, is null, or any exception occurs generating the JSON
    • getTreeFromObject

      public static com.fasterxml.jackson.databind.JsonNode getTreeFromObject(Object o)
      Convert an object into a JSON tree.
      Parameters:
      o - the object to convert
      Returns:
      the JSON tree, or null if o is null, or any exception occurs generating the JSON
      Since:
      1.1
    • getStringMapFromObject

      public static Map<String,Object> getStringMapFromObject(Object o)
      Convert an object into a Map with string keys.
      Parameters:
      o - the object to convert
      Returns:
      the map, or null if node is not a JSON object, is null, or any exception occurs generating the JSON
      Since:
      1.1
    • writeMetadata

      public static void writeMetadata(com.fasterxml.jackson.core.JsonGenerator generator, GeneralDatumMetadata meta) throws IOException
      Write metadata to a JSON generator.
      Parameters:
      generator - The generator to write to.
      meta - The metadata to write.
      Throws:
      IOException - if any IO error occurs
    • parseBigDecimalAttribute

      public static BigDecimal parseBigDecimalAttribute(com.fasterxml.jackson.databind.JsonNode node, String key)
      Parse a BigDecimal from a JSON object attribute value.
      Parameters:
      node - the JSON node (e.g. object)
      key - the attribute key to obtain from node
      Returns:
      the parsed BigDecimal, or null if an error occurs or the specified attribute key is not available
    • parseDateAttribute

      public static <T> T parseDateAttribute(com.fasterxml.jackson.core.TreeNode node, String key, DateTimeFormatter dateFormat, TemporalQuery<T> query)
      Parse a date from a JSON object attribute value.

      If the date cannot be parsed, null will be returned.

      Type Parameters:
      T - the date type
      Parameters:
      node - the JSON node (e.g. object)
      key - the attribute key to obtain from node
      dateFormat - the date format to use to parse the date string
      query - the temporal query, e.g. Instant::from
      Returns:
      the parsed date instance, or null if an error occurs or the specified attribute key is not available
      Since:
      2.0
    • parseIntegerAttribute

      public static Integer parseIntegerAttribute(com.fasterxml.jackson.databind.JsonNode node, String key)
      Parse a Integer from a JSON object attribute value. If the Integer cannot be parsed, null will be returned.
      Parameters:
      node - the JSON node (e.g. object)
      key - the attribute key to obtain from node node
      Returns:
      the parsed Integer, or null if an error occurs or the specified attribute key is not available
    • parseLongAttribute

      public static Long parseLongAttribute(com.fasterxml.jackson.databind.JsonNode node, String key)
      Parse a Long from a JSON object attribute value. If the Long cannot be parsed, null will be returned.
      Parameters:
      node - the JSON node (e.g. object)
      key - the attribute key to obtain from node node
      Returns:
      the parsed Long, or null if an error occurs or the specified attribute key is not available
    • parseStringAttribute

      public static String parseStringAttribute(com.fasterxml.jackson.databind.JsonNode node, String key)
      Parse a String from a JSON object attribute value. If the String cannot be parsed, null will be returned.
      Parameters:
      node - the JSON node (e.g. object)
      key - the attribute key to obtain from node node
      Returns:
      the parsed String, or null if an error occurs or the specified attribute key is not available
    • newObjectMapper

      public static com.fasterxml.jackson.databind.ObjectMapper newObjectMapper()
      Create a new ObjectMapper based on the default internal configuration used by other methods in this class.
      Returns:
      a new ObjectMapper
      Since:
      1.1
    • newDatumObjectMapper

      public static com.fasterxml.jackson.databind.ObjectMapper newDatumObjectMapper()
      Create a new ObjectMapper based on the default internal configuration used by other methods in this class.
      Returns:
      a new ObjectMapper
      Since:
      2.0
    • newObjectMapper

      public static com.fasterxml.jackson.databind.ObjectMapper newObjectMapper(com.fasterxml.jackson.core.JsonFactory jsonFactory)
      Create a new ObjectMapper based on the internal configuration used by other methods in this class.
      Parameters:
      jsonFactory - the JSON factory to use
      Returns:
      a new ObjectMapper
      Since:
      2.0
    • newDatumObjectMapper

      public static com.fasterxml.jackson.databind.ObjectMapper newDatumObjectMapper(com.fasterxml.jackson.core.JsonFactory jsonFactory)
      Create a new ObjectMapper based on the internal configuration used by other methods in this class.
      Parameters:
      jsonFactory - the JSON factory to use
      Returns:
      a new ObjectMapper
      Since:
      2.0
    • parseStringArray

      public static String[] parseStringArray(com.fasterxml.jackson.core.JsonParser p) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
      Parse a JSON array of scalar values into a string array.
      Parameters:
      p - the parser
      Returns:
      the parsed string array
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonProcessingException - if any processing exception occurs
    • writeStringArray

      public static void writeStringArray(com.fasterxml.jackson.core.JsonGenerator generator, String[] array) throws IOException, com.fasterxml.jackson.core.JsonGenerationException
      Write a string array as a JSON array of strings.
      Parameters:
      generator - the generator to write to
      array - the array to write
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonGenerationException - if any generation exception occurs
    • writeStringArrayField

      public static void writeStringArrayField(com.fasterxml.jackson.core.JsonGenerator generator, String fieldName, String[] array) throws IOException, com.fasterxml.jackson.core.JsonGenerationException
      Write a string array as a JSON object field that is an array of strings.
      Parameters:
      generator - the generator to write to
      fieldName - the field name
      array - the array to write
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonGenerationException - if any generation exception occurs
    • writeStringArrayValues

      public static void writeStringArrayValues(com.fasterxml.jackson.core.JsonGenerator generator, String[] array, int count) throws IOException
      Write a fixed number of string array values as JSON array numbers.

      This method does not write any starting or ending JSON array, it only writes the values. It always writes count values, regardless of the length of array. JSON null values will be written for any missing array values.

      Parameters:
      generator - the generator to write to
      array - the array values to write
      count - the number of string values to write
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonGenerationException - if any generation exception occurs
      Since:
      2.1
    • writeDecimalArray

      public static void writeDecimalArray(com.fasterxml.jackson.core.JsonGenerator generator, BigDecimal[] array) throws IOException, com.fasterxml.jackson.core.JsonGenerationException
      Write a string array as a JSON array of numbers.
      Parameters:
      generator - the generator to write to
      array - the array to write
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonGenerationException - if any generation exception occurs
    • writeDecimalArrayValues

      public static void writeDecimalArrayValues(com.fasterxml.jackson.core.JsonGenerator generator, BigDecimal[] array, int count) throws IOException
      Write a fixed number of decimal array values as JSON array numbers.

      This method does not write any starting or ending JSON array, it only writes the values. It always writes count values, regardless of the length of array. JSON null values will be written for any missing array values.

      Parameters:
      generator - the generator to write to
      array - the array values to write
      count - the number of string values to write
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonGenerationException - if any generation exception occurs
      Since:
      2.1
    • writeNumberField

      public static void writeNumberField(com.fasterxml.jackson.core.JsonGenerator gen, String fieldName, Number value) throws IOException
      Write a number field value using the smallest possible number type.

      If value is null then nothing will be generated.

      Parameters:
      gen - the JSON generator
      fieldName - the field name
      value - the number value
      Throws:
      IOException - if any IO error occurs
      Since:
      2.0
    • iso8610Timestamp

      public static Instant iso8610Timestamp(String timestamp)
      Parse an ISO 8601 timestamp value into an Instant.
      Parameters:
      timestamp - the timestamp value
      Returns:
      the instant, or null if timestamp is null, empty, or cannot be parsed
      Since:
      2.0
    • writeIso8601Timestamp

      public static void writeIso8601Timestamp(com.fasterxml.jackson.core.JsonGenerator gen, String fieldName, Instant value) throws IOException
      Write a timestamp field value in ISO 8601 form.

      If value is null then nothing will be generated.

      Parameters:
      gen - the JSON generator
      fieldName - the field name
      value - the instant value
      Throws:
      IOException - if any IO error occurs
      Since:
      2.0
    • writeBitmaskValue

      public static void writeBitmaskValue(com.fasterxml.jackson.core.JsonGenerator gen, String fieldName, Set<? extends Bitmaskable> value) throws IOException
      Write a bitmask set as a field number value.

      If value is null or empty then nothing will be generated.

      Parameters:
      gen - the JSON generator
      fieldName - the field name
      value - the instant value
      Throws:
      IOException - if any IO error occurs
      Since:
      2.0
    • parseDecimal

      public static BigDecimal parseDecimal(com.fasterxml.jackson.core.JsonParser p) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
      Parse a JSON numeric value into a BigDecimal.
      Parameters:
      p - the parser
      Returns:
      the decimal array
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonProcessingException - if any processing exception occurs
    • parseDecimalArray

      public static BigDecimal[] parseDecimalArray(com.fasterxml.jackson.core.JsonParser p) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
      Parse a JSON array of numeric values into a BigDecimal array.
      Parameters:
      p - the parser
      Returns:
      the decimal array
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonProcessingException - if any processing exception occurs
    • parseSimpleMap

      public static Map<String,?> parseSimpleMap(com.fasterxml.jackson.core.JsonParser p) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
      Parse a simple Map from a JSON object.
      Parameters:
      p - the parser
      Returns:
      the Map, or null if no Map can be parsed
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonProcessingException - if any processing exception occurs
      Since:
      2.0
    • writeSimpleMap

      public static void writeSimpleMap(com.fasterxml.jackson.core.JsonGenerator generator, Map<String,?> value) throws IOException, com.fasterxml.jackson.core.JsonGenerationException
      Write a simple Map as a JSON object.

      Only primitive object values are supported.

      Parameters:
      generator - the generator to write to
      value - the map to write
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonGenerationException - if any generation exception occurs
      Since:
      2.0
    • parseIndexedFieldsObject

      public static void parseIndexedFieldsObject(com.fasterxml.jackson.core.JsonParser p, com.fasterxml.jackson.databind.DeserializationContext ctxt, Object[] data, Map<String,? extends IndexedField> fields) throws IOException, com.fasterxml.jackson.core.JsonProcessingException
      Parse a JSON object using a map of IndexedField values.
      Parameters:
      p - the parser
      ctxt - the context
      data - the data array to populate, based on each IndexedField.getIndex() value
      fields - the mapping of field names to associated fields
      Throws:
      IOException - if any IO error occurs
      com.fasterxml.jackson.core.JsonProcessingException - if any processing exception occurs