From 6a7b42373cc1819c1c753bad7ce193d919277d0f Mon Sep 17 00:00:00 2001 From: Henrique Prange Date: Thu, 5 Aug 2021 22:33:04 -0300 Subject: [PATCH] Add utility method to turn objects into dictionaries with custom keys The `ERXDictionaryUtilities.dictionaryFromObjectWithKeyMappings` creates a dictionary from an object according to the given key mappings, skipping `null` values. Usage: ``` NSDictionary data = dictionaryFromObjectWithKeyMappings(eo, NSDictionary.of("key1", EO.ATTRIBUTE1, "key2", EO.ATTRIBUTE2); ``` Result: ``` { "key1" = "valueForAttribute1"; "key2" = "valueForAttribute2"; } ``` --- .../foundation/ERXDictionaryUtilities.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Frameworks/Core/ERExtensions/Sources/er/extensions/foundation/ERXDictionaryUtilities.java b/Frameworks/Core/ERExtensions/Sources/er/extensions/foundation/ERXDictionaryUtilities.java index 7c2d7ced5a8..2e8fdda6845 100644 --- a/Frameworks/Core/ERExtensions/Sources/er/extensions/foundation/ERXDictionaryUtilities.java +++ b/Frameworks/Core/ERExtensions/Sources/er/extensions/foundation/ERXDictionaryUtilities.java @@ -9,6 +9,7 @@ import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Enumeration; +import java.util.Map.Entry; import com.webobjects.appserver.WOMessage; import com.webobjects.eocontrol.EOKeyValueCoding; @@ -180,6 +181,43 @@ public static NSDictionary dictionaryFromObjectWithKeys(Object o public static NSDictionary dictionaryFromObjectWithKeys(Object object, ERXKey... keys) { return dictionaryFromObjectWithKeys(object, (NSArray) new NSArray(keys).valueForKey("key")); } + + /** + * Creates a dictionary from an object according to the given key mappings, skipping null values. + *

+ * Usage: + * + *

+     * NSDictionary<String, Object> data = dictionaryFromObjectWithKeyMappings(eo, NSDictionary.of("key1", EO.ATTRIBUTE1, "key2", EO.ATTRIBUTE2);
+     * 
+ * + * Result: + * + *
+     * {"key1" = "valueForAttribute1"; "key2" = "valueForAttribute2"}
+     * 
+ * + * @param object + * object to pull the values from + * @param keyMappings + * keypath mapping for keys + * @return Returns a {@code NSDictionary} containing all of the object-key pairs. + */ + public static NSMutableDictionary dictionaryFromObjectWithKeyMappings(Object object, NSDictionary> keyMappings) { + NSMutableDictionary result = new NSMutableDictionary<>(); + + for (Entry> entry : keyMappings.entrySet()) { + String key = entry.getKey(); + ERXKey keypath = entry.getValue(); + Object value = keypath.valueInObject(object); + + if (value != null) { + result.setObjectForKey(value, key); + } + } + + return result; + } // if you're keys are not all strings, this method will throw. public static NSArray stringKeysSortedAscending(final NSDictionary d) {