@@ -51,20 +51,32 @@ private POJODefinition _introspectDefinition(Class<?> beanType,
51
51
// For Serialization OTOH we need sorting (although would probably
52
52
// be better to sort after the fact, maybe in future)
53
53
54
- Map <String ,PropBuilder > propsByName = forSerialization ?
55
- new TreeMap <>() : new LinkedHashMap <>();
56
-
54
+ Map <String ,PropBuilder > propsByName ;
55
+ // 04-Nov-2024, tatu [jackson-jr#171] May need to retain order
56
+ // for Record serialization too
57
+ final boolean recordSerInDeclOrder = isRecord && forSerialization
58
+ && JSON .Feature .WRITE_RECORD_FIELDS_IN_DECLARATION_ORDER .isEnabled (features );
59
+
60
+ // Alphabetic ordering unnecessary for Deserialization (and some serialization too)
61
+ if (forSerialization && !recordSerInDeclOrder ) {
62
+ propsByName = new TreeMap <>();
63
+ } else {
64
+ propsByName = new LinkedHashMap <>();
65
+ }
66
+
57
67
final BeanConstructors constructors ;
58
68
if (forSerialization ) {
69
+ if (recordSerInDeclOrder ) {
70
+ Constructor <?> canonical = _getCanonicalRecordConstructor (beanType );
71
+ for (Parameter ctorParam : canonical .getParameters ()) {
72
+ _propFrom (propsByName , ctorParam .getName ());
73
+ }
74
+ }
59
75
constructors = null ;
60
76
} else {
61
77
constructors = new BeanConstructors (beanType );
62
78
if (isRecord ) {
63
- Constructor <?> canonical = RecordsHelpers .findCanonicalConstructor (beanType );
64
- if (canonical == null ) { // should never happen
65
- throw new IllegalArgumentException (
66
- "Unable to find canonical constructor of Record type `" +beanType .getClass ().getName ()+"`" );
67
- }
79
+ Constructor <?> canonical = _getCanonicalRecordConstructor (beanType );
68
80
constructors .addRecordConstructor (canonical );
69
81
// And then let's "seed" properties to ensure correct ordering
70
82
// of Properties wrt Canonical constructor parameters:
@@ -105,6 +117,15 @@ private POJODefinition _introspectDefinition(Class<?> beanType,
105
117
return new POJODefinition (beanType , props , constructors );
106
118
}
107
119
120
+ private Constructor <?> _getCanonicalRecordConstructor (Class <?> beanType ) {
121
+ Constructor <?> canonical = RecordsHelpers .findCanonicalConstructor (beanType );
122
+ if (canonical == null ) { // should never happen
123
+ throw new IllegalArgumentException (
124
+ "Unable to find canonical constructor of Record type `" +beanType .getClass ().getName ()+"`" );
125
+ }
126
+ return canonical ;
127
+ }
128
+
108
129
private static void _introspect (Class <?> currType , Map <String , PropBuilder > props ,
109
130
int features , boolean isRecord )
110
131
{
0 commit comments