Skip to content

Commit

Permalink
Fix #817: support for Java record objects
Browse files Browse the repository at this point in the history
  • Loading branch information
BalusC committed May 11, 2024
1 parent ee1d6de commit 5f65eaf
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/main/java/org/omnifaces/util/Json.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.RecordComponent;
import java.time.temporal.Temporal;
import java.util.Collection;
import java.util.Date;
Expand Down Expand Up @@ -119,6 +120,9 @@ else if (object instanceof Map<?, ?>) {
else if (object instanceof Class<?>) {
encodeString(((Class<?>) object).getName(), builder);
}
else if (object instanceof Record) {
encodeRecord((Record) object, builder, propertyNameFormatter);
}
else {
encodeBean(object, builder, propertyNameFormatter);
}
Expand Down Expand Up @@ -187,6 +191,38 @@ private static void encodeMap(Map<?, ?> map, StringBuilder builder, UnaryOperato
builder.append('}');
}

/**
* Encode a Java record as JS object.
*/
private static void encodeRecord(Record record, StringBuilder builder, UnaryOperator<String> propertyNameFormatter) {
builder.append('{');
int i = 0;

for (RecordComponent component : record.getClass().getRecordComponents()) {
Object value;

try {
value = component.getAccessor().invoke(record);
}
catch (Exception e) {
throw new IllegalArgumentException(
format(ERROR_INVALID_GETTER, component.getName(), record.getClass()), e);
}

if (value != null) {
if (i++ > 0) {
builder.append(',');
}

encodePropertyName(component.getName(), builder, propertyNameFormatter);
builder.append(':');
encode(value, builder, propertyNameFormatter);
}
}

builder.append('}');
}

/**
* Encode a Java bean as JS object.
*/
Expand Down

0 comments on commit 5f65eaf

Please sign in to comment.