Skip to content

[BUG] global SnakeCase naming strategy is not applied to Java records #7656

@artpaym

Description

@artpaym

Description

When fastjson2 global writer naming strategy is configured with PropertyNamingStrategy.SnakeCase, serialization applies snake_case naming to normal Java class fields, but not to Java records.

This causes DTOs implemented as records to serialize camelCase fields into final JSON even though global snake_case output is configured.

Environment

  • Verified versions: 2.0.60, 2.0.61, 2.0.62
  • Java: 21

Reproduction

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONFactory;
import com.alibaba.fastjson2.PropertyNamingStrategy;

record RecordDto(String currencyCode) {}

class ClassDto {
    public String currencyCode = "840";
}

JSONFactory.getDefaultObjectWriterProvider()
        .setNamingStrategy(PropertyNamingStrategy.SnakeCase);

System.out.println(JSON.toJSONString(new RecordDto("840")));
System.out.println(JSON.toJSONString(new ClassDto()));

Expected Result

Both DTOs serialize using snake_case:

{"currency_code":"840"}
{"currency_code":"840"}

Actual Result

Only the normal class is snake-cased. The record remains camelCase:

{"currencyCode":"840"}
{"currency_code":"840"}

Workaround

Use a normal Java class instead of a record, or annotate each affected record component with @JSONField(name = "snake_case_name").

Additional Notes

Also verified that @JSONType(naming = PropertyNamingStrategy.SnakeCase) and JSONWriter.Feature.FieldBased did not change the record output in the local probe.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions