Class JsonHelper
One specific note on methods that accept paths. The syntax used to indicate array paths consists of the
array property name, followed by a period, followed by the array index in square brackets. For example, if
to find the first value in an array property luckyNumbers, the path is luckyNumbers.[0].
Similarly, to find the 13th lucky number the path is luckyNumbers.[12].
Paths for nested JSON objects follow the syntax objectName.propertyName; for JSON that contains a
homeAddress object that contains a zipCode, the path is homeAddress.zipCode.
- Implementation Note:
- This uses Jackson to perform JSON mapping to and from objects, so Jackson will need to be available
at runtime. In addition, if you use the no-args constructor, this relies on Dropwizard's
Jacksonclass which does a bunch of configuration on the default JacksonObjectMapper. So you would also need Dropwizard available at runtime as well, specificallydropwizard-jackson.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumDescribes how objects are to be merged.static enumRepresents an output format when serializing an object to JSON. -
Constructor Summary
ConstructorsConstructorDescriptionCreate a new instance using anObjectMappercreated usingnewDropwizardObjectMapper().JsonHelper(com.fasterxml.jackson.databind.ObjectMapper objectMapper) Create a new instance using the givenObjectMapper. -
Method Summary
Modifier and TypeMethodDescriptionstatic com.fasterxml.jackson.databind.ObjectMapperconfigureForMillisecondDateTimestamps(com.fasterxml.jackson.databind.ObjectMapper mapper) Configure the givenObjectMapperto read and write timestamps as milliseconds.<T> TConverts the given object to an object of the target type described by theTypeReference.<T> TConverts the given object to an object of the target type.convertToMap(Object fromObject) Converts the given object to a map with String keys and Object values.<K,V> Map<K, V> convertToMap(Object fromObject, com.fasterxml.jackson.core.type.TypeReference<Map<K, V>> targetMapType) Converts the given object to a map using the givenTypeReference.<T> Tcopy(T object) Copies the given object by converting to JSON and then converting the JSON back to an object of the same class as the copied object.<T,R> R Copies the given object by converting to JSON and then converting the JSON back to an object of the given target class.<T,R> R copyIgnoringPaths(T object, Class<R> targetClass, String... ignoredPaths) Copies the given object by converting to JSON, ignoring the given paths, and then converting the JSON back to an object of the given target class.detectJson(@Nullable String content) Use Jackson's data format detection to determine if the given content is JSON, assuming UTF-8 as the charset.detectJson(@Nullable String content, Charset charset) Use Jackson's data format detection to determine if the given content is JSON.com.fasterxml.jackson.databind.ObjectMapperProvides direct access to the underlying object mapper.<T> TGet the value at the given path in the object, with the type as the given target class.<T> TGet the value at the given path in the object, with the type as the given target class.<T> TGet the value at the given path in the JSON, with the type as the given target class.<T> TGet the value at the given path in the JSON, with the type as the given target class.booleanUse Jackson's data format detection to determine if the given content is JSON, assuming UTF-8 as the charset.booleanUse Jackson's data format detection to determine if the given content is JSON.Compare an object to an arbitrary number of other objects via their JSON differences.Compare a JSON object to an arbitrary number of other objects via their JSON differences.Compare two objects via their JSON differences, optionally ignoring one or more paths.booleanjsonEquals(Object... objects) Compare the JSON representation of multiple objects.booleanjsonEqualsIgnoringPaths(Object object1, Object object2, String... ignoredPaths) Compare the JSON representations of two objects, optionally ignoring paths.<T> booleanjsonPathsEqual(Object object1, Object object2, String path, Class<T> targetClass) Compare the values at a given path in two objects.listObjectPaths(@Nullable Object object) Parse the given object as JSON, and return a list containing the property paths in the object.com.fasterxml.jackson.databind.JsonNodemergeNodes(com.fasterxml.jackson.databind.JsonNode destinationNode, com.fasterxml.jackson.databind.JsonNode updateNode, JsonHelper.MergeOption... mergeOptions) Updates (mutates)destinationNodewith values fromupdateNode.<T> TmergeObjects(T originalObject, Object updateObject, JsonHelper.MergeOption... mergeOptions) Merge values inupdateObjectinto the original object, using the given merge options.static JsonHelperstatic com.fasterxml.jackson.databind.ObjectMapperCreates a newObjectMapperconfigured using the DropwizardJackson.newObjectMapper()factory method.com.fasterxml.jackson.databind.JsonNoderemovePath(@Nullable Object object, String path) Remove the given path from the object.Parse the given object as JSON, then flatten all its properties to a map whose keys are the object property names and whose values are converted to Strings.Parse the given object as JSON, then flatten all its properties to a map whose keys are the object property names and whose values are converted to the givenvalueClasstype.Convert the given object to JSON using theJsonHelper.OutputFormat.DEFAULTformat.toJson(@Nullable Object object, JsonHelper.OutputFormat format) Convert the given object to JSON using the given format.toJson(@Nullable Object object, JsonHelper.OutputFormat format, @Nullable Class<?> jsonView) Convert the given object to JSON using the given format and optionally a class representing theJsonViewto use.toJsonFromKeyValuePairs(Object... kvPairs) Consider the given arguments as key/value pairs, and convert those pairs to a JSON representation.toJsonIgnoringPaths(@Nullable Object object, String... ignoredPaths) Convert the given object to JSON, but ignoring (excluding) the given paths.Convert the given JSON into a map with String keys and Object values.<K,V> Map<K, V> Convert the given JSON into a map with keys of typeKand values of typeV.<T> TConvert the given JSON into an object of typeTusing the givenTypeReference.<T> TConvert the given JSON into the specified type.<T> List<T>toObjectList(@Nullable String json, com.fasterxml.jackson.core.type.TypeReference<List<T>> targetListType) Convert the given JSON into a List of objects of typeT.<T> Optional<T>toObjectOptional(@Nullable String json, Class<T> targetClass) Return an Optional that will contain an object of the expected typeT, or an empty Optional if the input JSON is blank<T> TtoObjectOrDefault(@Nullable String json, Class<T> clazz, T defaultValue) Convert the given JSON into the specified type, or return the given default value if input JSON is blank.<T> TtoObjectOrSupply(@Nullable String json, Class<T> clazz, Supplier<T> defaultValueSupplier) Convert the given JSON into the specified type, or return the supplied default value if input JSON is blank.<T> TupdatePath(@Nullable Object object, String path, Object value, Class<T> targetClass) Update the given path in the object with the new value, converting to the target class.
-
Constructor Details
-
JsonHelper
public JsonHelper()Create a new instance using anObjectMappercreated usingnewDropwizardObjectMapper(). -
JsonHelper
public JsonHelper(com.fasterxml.jackson.databind.ObjectMapper objectMapper) Create a new instance using the givenObjectMapper.- Parameters:
objectMapper- the ObjectMapper to use
-
-
Method Details
-
newDropwizardJsonHelper
- Returns:
- a new JsonHelper instance
-
newDropwizardObjectMapper
public static com.fasterxml.jackson.databind.ObjectMapper newDropwizardObjectMapper()Creates a newObjectMapperconfigured using the DropwizardJackson.newObjectMapper()factory method. It also configures the returned mapper to read and write timestamps as milliseconds.- Returns:
- a new ObjectMapper
- See Also:
-
DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDSSerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDSconfigureForMillisecondDateTimestamps(ObjectMapper)
-
configureForMillisecondDateTimestamps
public static com.fasterxml.jackson.databind.ObjectMapper configureForMillisecondDateTimestamps(com.fasterxml.jackson.databind.ObjectMapper mapper) Configure the givenObjectMapperto read and write timestamps as milliseconds.- Parameters:
mapper- theObjectMapperto change- Returns:
- the same instance, configured to write/read timestamps as milliseconds
-
getObjectMapper
public com.fasterxml.jackson.databind.ObjectMapper getObjectMapper()Provides direct access to the underlying object mapper. Care should be taken when accessing theObjectMapperdirectly, particularly if any changes are made to how objects are serialized/de-serialized.- Returns:
- the object mapper; any changes made to it will potentially change the behavior of this JsonHelper instance
-
isJson
Use Jackson's data format detection to determine if the given content is JSON, assuming UTF-8 as the charset.- Parameters:
content- the content to check- Returns:
- true if detected as JSON, false otherwise (including if content is null or blank, or if an exception is thrown detecting the format)
-
isJson
Use Jackson's data format detection to determine if the given content is JSON.- Parameters:
content- the content to checkcharset- the character set to use- Returns:
- true if detected as JSON, false otherwise (including if content is null or blank, or if an exception is thrown detecting the format)
- See Also:
-
DataFormatDetector.findFormat(byte[])
-
detectJson
Use Jackson's data format detection to determine if the given content is JSON, assuming UTF-8 as the charset.- Parameters:
content- the content to check- Returns:
- the detection result
-
detectJson
Use Jackson's data format detection to determine if the given content is JSON.- Parameters:
content- the content to checkcharset- the character set to use- Returns:
- the detection result
-
toJson
Convert the given object to JSON using theJsonHelper.OutputFormat.DEFAULTformat.- Parameters:
object- the object to convert- Returns:
- a JSON representation of the given object, or
nullif the given object isnull
-
toJson
Convert the given object to JSON using the given format.- Parameters:
object- the object to convertformat- the format to use- Returns:
- a JSON representation of the given object, or
nullif the given object isnull
-
toJson
public String toJson(@Nullable Object object, JsonHelper.OutputFormat format, @Nullable Class<?> jsonView) Convert the given object to JSON using the given format and optionally a class representing theJsonViewto use.- Parameters:
object- the object to convertformat- the format to usejsonView- the nullableJsonViewclass- Returns:
- a JSON representation of the given object, or
nullif the given object isnull
-
toJsonFromKeyValuePairs
Consider the given arguments as key/value pairs, and convert those pairs to a JSON representation.- Parameters:
kvPairs- the objects to treat as key/value pairs- Returns:
- the JSON representation
- Throws:
IllegalArgumentException- if an odd number of arguments is supplied
-
toJsonIgnoringPaths
Convert the given object to JSON, but ignoring (excluding) the given paths.- Parameters:
object- the object to convertignoredPaths- the paths to ignore/exclude- Returns:
- the JSON representation without the ignored paths
-
toObject
Convert the given JSON into the specified type.- Type Parameters:
T- the object type- Parameters:
json- the JSON contenttargetClass- the type of object to convert into- Returns:
- a new instance of the given type, or
nullif the given input JSON is blank
-
toObjectOrDefault
Convert the given JSON into the specified type, or return the given default value if input JSON is blank.- Type Parameters:
T- the object type- Parameters:
json- the JSON contentclazz- the type of object to convert intodefaultValue- the default value to use if necessary- Returns:
- a new instance of the given type, or return
defaultValueif the given input JSON is blank
-
toObjectOrSupply
public <T> T toObjectOrSupply(@Nullable String json, Class<T> clazz, Supplier<T> defaultValueSupplier) Convert the given JSON into the specified type, or return the supplied default value if input JSON is blank.- Type Parameters:
T- the object type- Parameters:
json- the JSON contentclazz- the type of object to convert intodefaultValueSupplier- the default valueSupplierto call if necessary- Returns:
- a new instance of the given type, or return the value supplied by
defaultValueSupplierif the given input JSON is blank
-
toObject
public <T> T toObject(@Nullable String json, com.fasterxml.jackson.core.type.TypeReference<T> targetType) Convert the given JSON into an object of typeTusing the givenTypeReference.- Type Parameters:
T- the object type- Parameters:
json- the JSON contenttargetType- theTypeReferencerepresenting the target object type- Returns:
- a new instance of the type encapsulated by the TypeReference, or
nullif the input JSON is blank
-
toObjectOptional
Return an Optional that will contain an object of the expected typeT, or an empty Optional if the input JSON is blank- Type Parameters:
T- the object type- Parameters:
json- the JSON contenttargetClass- the type of object to convert into- Returns:
- an Optional that may contain a converted object
-
toObjectList
public <T> List<T> toObjectList(@Nullable String json, com.fasterxml.jackson.core.type.TypeReference<List<T>> targetListType) Convert the given JSON into a List of objects of typeT.- Type Parameters:
T- the object type- Parameters:
json- the JSON contenttargetListType- theTypeReferencerepresenting the list target type- Returns:
- a list containing objects of the given type, or
nullif the input is blank
-
toMap
Convert the given JSON into a map with String keys and Object values.- Parameters:
json- the JSON content- Returns:
- the parsed map, or
nullif the input JSON is blank
-
toMap
public <K,V> Map<K,V> toMap(@Nullable String json, com.fasterxml.jackson.core.type.TypeReference<Map<K, V>> targetMapType) Convert the given JSON into a map with keys of typeKand values of typeV.- Type Parameters:
K- the type of keys in the mapV- the type of values in the map- Parameters:
json- the JSON contenttargetMapType- theTypeReferencerepresenting the target map type- Returns:
- the parsed map, or
nullif the input JSON is blank
-
toFlatMap
Parse the given object as JSON, then flatten all its properties to a map whose keys are the object property names and whose values are converted to Strings.For more details on the behavior, see
toFlatMap(Object, Class).- Parameters:
object- the object to flatten- Returns:
- a map with string keys and values converted to strings, or
nullif the given object isnull
-
toFlatMap
Parse the given object as JSON, then flatten all its properties to a map whose keys are the object property names and whose values are converted to the givenvalueClasstype. In practice, this will often just beObject.classbut could be a more specific type, e.g. if you have a map containing student names and grades then the values could all be of typeDouble.This also flattens arrays/collections and maps. Flattened arrays use the following syntax:
arrayPropertyName.[index]. For example,luckyNumbers.[0]is the first element in a collection namedluckyNumbers. For maps, the syntax is:mapPropertyName.key. For example,emailAddresses.homecontains the value in theemailAddressesmap under the keyhome.- Type Parameters:
T- the generic type of the map values- Parameters:
object- the object to flattenvalueClass- the target class for the map's values- Returns:
- a map with string keys and values converted to the specified type, or
nullif the given object isnull
-
copy
public <T> T copy(T object) Copies the given object by converting to JSON and then converting the JSON back to an object of the same class as the copied object.- Type Parameters:
T- the type of object being copied- Parameters:
object- the object to copy- Returns:
- the copied object of the target class
-
copy
Copies the given object by converting to JSON and then converting the JSON back to an object of the given target class.- Type Parameters:
T- the type of object being copiedR- the type of object to copy into- Parameters:
object- the object to copytargetClass- the target class (it may be different from the original)- Returns:
- the copied object of the target class
-
copyIgnoringPaths
Copies the given object by converting to JSON, ignoring the given paths, and then converting the JSON back to an object of the given target class.- Type Parameters:
T- the type of object being copiedR- the type of object to copy into- Parameters:
object- the object to copytargetClass- the target class (it may be different from the original)ignoredPaths- the paths to ignore during the copy- Returns:
- the copied object of the target class
-
convert
Converts the given object to an object of the target type.- Type Parameters:
T- the target type- Parameters:
fromObject- the object to converttargetType- the type of object to convert to- Returns:
- a new instance of the target type
- See Also:
-
ObjectMapper.convertValue(Object, Class)
-
convert
public <T> T convert(Object fromObject, com.fasterxml.jackson.core.type.TypeReference<T> targetType) Converts the given object to an object of the target type described by theTypeReference.- Type Parameters:
T- the target type- Parameters:
fromObject- the object to converttargetType- aTypeReferencethat describes the target type- Returns:
- a new instance of the target type
- See Also:
-
ObjectMapper.convertValue(Object, TypeReference)
-
convertToMap
Converts the given object to a map with String keys and Object values.- Parameters:
fromObject- the object to convert- Returns:
- a new map instance
-
convertToMap
public <K,V> Map<K,V> convertToMap(Object fromObject, com.fasterxml.jackson.core.type.TypeReference<Map<K, V>> targetMapType) Converts the given object to a map using the givenTypeReference.Unless you have specialized requirements, usually
convertToMap(Object)will be what you want.- Type Parameters:
K- the type of keys in the mapV- the type of values in the map- Parameters:
fromObject- the object to converttargetMapType- theTypeReferencedescribing the target map type- Returns:
- a new map instance
-
getPath
Get the value at the given path in the object, with the type as the given target class.- Type Parameters:
T- the return type- Parameters:
object- the object to searchpath- the path within the object (e.g. "homeAddress.zipCode")targetClass- the type associated with the given path- Returns:
- an instance of the specified target class
-
getPath
Get the value at the given path in the JSON, with the type as the given target class.- Type Parameters:
T- the return type- Parameters:
json- the JSON to searchpath- the path within the object (e.g. "homeAddress.zipCode")targetClass- the type associated with the given path- Returns:
- an instance of the specified target class
-
getPath
public <T> T getPath(Object object, String path, com.fasterxml.jackson.core.type.TypeReference<T> targetType) Get the value at the given path in the object, with the type as the given target class.- Type Parameters:
T- the return type- Parameters:
object- the object to searchpath- the path within the object (e.g. "homeAddress.zipCode")targetType- the type associated with the given path- Returns:
- an instance of the specified target class
-
getPath
public <T> T getPath(String json, String path, com.fasterxml.jackson.core.type.TypeReference<T> targetType) Get the value at the given path in the JSON, with the type as the given target class.- Type Parameters:
T- the return type- Parameters:
json- the JSON to searchpath- the path within the object (e.g. "homeAddress.zipCode")targetType- the type associated with the given path- Returns:
- an instance of the specified target class
-
removePath
Remove the given path from the object.- Parameters:
object- the object from which to remove a pathpath- the path to remove- Returns:
- a
JsonNodewith the given path removed
-
updatePath
Update the given path in the object with the new value, converting to the target class.- Type Parameters:
T- the type of the input object- Parameters:
object- the original objectpath- the path to updatevalue- the new value to usetargetClass- the type of object to return- Returns:
- a new instance of the given target type
-
jsonDiff
public Map<String,List<String>> jsonDiff(@Nullable Object object1, @Nullable Object object2, String... ignoredPaths) Compare two objects via their JSON differences, optionally ignoring one or more paths. The diff is from the perspective of the first object.The returned map of differences has keys that are the properties that are different. The map values are the values for the corresponding key/property in the first and second objects, respectively.
NOTE: This is an expensive operation so be careful of using it in production code in areas where performance is critical.
- Parameters:
object1- the first objectobject2- the second objectignoredPaths- the paths to ignore in the comparison- Returns:
- a map containing a list of differences
-
jsonDiff
Compare an object to an arbitrary number of other objects via their JSON differences. The diff is from the perspective of the first object in the given list.The returned map of differences has keys that are the properties that are different. The map values are the values for the corresponding key/property in the first and subsequent objects, respectively.
NOTE: This is an expensive operation so be careful of using it in production code in areas where performance is critical.
- Parameters:
objectList- the list of objects to compare; the first object is the reference objectignoredPaths- the paths to ignore in the comparison- Returns:
- a map containing a list of differences
-
jsonDiff
Compare a JSON object to an arbitrary number of other objects via their JSON differences. The diff is from the perspective of the first JSON object in the given list.The returned map of differences has keys that are the properties that are different. The map values are the values for the corresponding key/property in the first and subsequent objects, respectively.
NOTE: This is an expensive operation so be careful of using it in production code in areas where performance is critical.
- Parameters:
listOfJson- the list of JSON objects to compare- Returns:
- map containing a list of differences
-
jsonEquals
Compare the JSON representation of multiple objects.- Parameters:
objects- the objects to compare- Returns:
- true if all the given objects have equal JSON representations
-
jsonEqualsIgnoringPaths
Compare the JSON representations of two objects, optionally ignoring paths.- Parameters:
object1- the first object to compareobject2- the second object to compareignoredPaths- the paths to ignore in the comparison- Returns:
- true if the objects have equal JSON representations, ignoring the given paths
-
jsonPathsEqual
public <T> boolean jsonPathsEqual(Object object1, Object object2, String path, Class<T> targetClass) Compare the values at a given path in two objects.- Type Parameters:
T- the object type for the given path- Parameters:
object1- the first objectobject2- the second objectpath- the path to comparetargetClass- the type of object at the given path- Returns:
- true if the two objects have an equal value at the given path; the two values are compared using
Objects.equals(Object, Object)
-
mergeObjects
public <T> T mergeObjects(T originalObject, Object updateObject, JsonHelper.MergeOption... mergeOptions) Merge values inupdateObjectinto the original object, using the given merge options.Note that the
originalObjectis not mutated in any way; it simply represents the original state to be updated with values fromupdateObject. BothoriginalObjectandupdateObjectare converted to JSON before merging.- Type Parameters:
T- the type of the merged object- Parameters:
originalObject- the object into which updates will be merged (only used to read original state)updateObject- the object containing updatesmergeOptions- zero or moreJsonHelper.MergeOption- Returns:
- a new instance of type T
- See Also:
-
mergeNodes
public com.fasterxml.jackson.databind.JsonNode mergeNodes(com.fasterxml.jackson.databind.JsonNode destinationNode, com.fasterxml.jackson.databind.JsonNode updateNode, JsonHelper.MergeOption... mergeOptions) Updates (mutates)destinationNodewith values fromupdateNode.- Parameters:
destinationNode- the node that will be updated (mutated)updateNode- the node containing updated valuesmergeOptions- zero or moreJsonHelper.MergeOption- Returns:
- the mutated
destinationNode - See Also:
-
listObjectPaths
Parse the given object as JSON, and return a list containing the property paths in the object. The paths include arrays, collections and maps.For details on the property path syntax, see
toFlatMap(Object, Class).- Parameters:
object- the object to list paths for- Returns:
- a list of the property paths
-