Skip to content

JSONObject does not work with records without field annotations #1015

Description

@MarcoMartins86

new JSONObject(object) or JSONObject.wrap(object) does not work if the object is a record without @JSONPropertyName on its fields.

The flow eventually reaches out to JSONObject.getKeyNameFromMethod(Method method), and looking into the version 20250517 code, we can see that:

JSONPropertyName annotation = getAnnotation(method, JSONPropertyName.class);
if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) {
    return annotation.value();
}
String key;
final String name = method.getName();
if (name.startsWith("get") && name.length() > 3) {
    key = name.substring(3);
} else if (name.startsWith("is") && name.length() > 2) {
    key = name.substring(2);
} else {
    return null;
}

If the field is not annotated with @JSONPropertyName and if it doesn't start with get or is, then it will return null.
Since records don't use prefixes on getters, it will always be represented as {} an empty object.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions