Skip to content

@JsonProperty on constructor parameter changes default field serialization order #3928

@pjfanning

Description

@pjfanning

Discussed in #3925

Originally posted by safdevke May 12, 2023
Hi, this is a trivial case that I came across. Using nested records changes the order of the properties in the serialized output. Here's a simple example:

public record NestedRecordOne(
    String id,

    String email,

    @JsonProperty(value = "yikes!")
    NestedRecordTwo nestedRecordTwo) {}
public record NestedRecordTwo (
    String id,

    String passport) {}
public static void main(String[] args) throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();
        NestedRecordTwo nestedRecordTwo = new NestedRecordTwo("2", "111110");
        NestedRecordOne nestedRecordOne = new NestedRecordOne("1", "[email protected]", nestedRecordTwo);

        objectMapper.writeValue(new File("nested-record.json"), nestedRecordOne);
    }

The output is:

{
    "yikes!": {
        "id": "2",
        "passport": "111110"
    },
    "id": "1",
    "email": "[email protected]"
}

Performing the same test on classes seems to work fine:

public class NestedClassOne {

    private String id;

    private String name;

    @JsonProperty(value = "all is fine!")
    private NestedClassTwo nestedClassTwo;

    // All args constructor + getters + setters
}
public class NestedClassTwo {

    private String id;

    // All args constructor + getters + setters
}
    NestedClassOne nestedClassOne = new NestedClassOne("1", new NestedClassTwo("2"), "test class");
    
    objectMapper.writeValue(new File("nested-class.json"), nestedClassOne);

Produces:

{
    "id": "1",
    "name": "test class",
    "all is fine!": {
        "id": "2"
    }
}

This could be easily fixed by using @JsonPropertyOrder. I wonder why it behaves this way for records. I didn't think this warranted creating an issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions