Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add utility method to turn objects into dictionaries with custom keys #957

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -180,6 +181,43 @@ public static NSDictionary<String, Object> dictionaryFromObjectWithKeys(Object o
public static NSDictionary<String, Object> dictionaryFromObjectWithKeys(Object object, ERXKey... keys) {
return dictionaryFromObjectWithKeys(object, (NSArray<String>) new NSArray<ERXKey>(keys).valueForKey("key"));
}

/**
* Creates a dictionary from an object according to the given key mappings, skipping null values.
* <p>
* Usage:
*
* <pre>
* NSDictionary&lt;String, Object&gt; data = dictionaryFromObjectWithKeyMappings(eo, NSDictionary.of("key1", EO.ATTRIBUTE1, "key2", EO.ATTRIBUTE2);
* </pre>
*
* Result:
*
* <pre>
* {"key1" = "valueForAttribute1"; "key2" = "valueForAttribute2"}
* </pre>
*
* @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<String, Object> dictionaryFromObjectWithKeyMappings(Object object, NSDictionary<String, ERXKey<?>> keyMappings) {
NSMutableDictionary<String, Object> result = new NSMutableDictionary<>();

for (Entry<String, ? extends ERXKey<?>> 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<String> stringKeysSortedAscending(final NSDictionary<String, ?> d) {
Expand Down