Skip to content

Commit 4dff70b

Browse files
committed
Add support for serializing "empty" Records (and tests)
1 parent 197c468 commit 4dff70b

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

src/main/java/com/fasterxml/jackson/databind/ser/BeanSerializerFactory.java

+6-1
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,12 @@ protected JsonSerializer<Object> constructBeanOrAddOnSerializer(SerializerProvid
463463
return prov.reportBadTypeDefinition(beanDesc, "Failed to construct BeanSerializer for %s: (%s) %s",
464464
beanDesc.getType(), e.getClass().getName(), e.getMessage());
465465
}
466-
if (ser == null) {
466+
if (ser == null) { // Means that no properties were found
467+
// 21-Aug-2020, tatu: Empty Records should be fine tho
468+
if (type.isRecordType()) {
469+
return builder.createDummy();
470+
}
471+
467472
// 06-Aug-2019, tatu: As per [databind#2390], we need to check for add-ons here,
468473
// before considering fallbacks
469474
ser = (JsonSerializer<Object>) findSerializerByAddonType(config, type, beanDesc, staticTyping);

src/test-jdk14/java/com/fasterxml/jackson/databind/RecordTest.java

+15-5
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ record JsonIgnoreRecord(int id, @JsonIgnore String name) {
3030
record JsonPropertyRenameRecord(int id, @JsonProperty("rename")String name) {
3131
}
3232

33+
record EmptyRecord() {
34+
}
35+
3336
private final ObjectMapper MAPPER = newJsonMapper();
3437

3538
/*
@@ -65,16 +68,23 @@ public void testRecordJavaType() {
6568
*/
6669

6770
public void testSerializeSimpleRecord() throws Exception {
68-
SimpleRecord record = new SimpleRecord(123, "Bob");
69-
70-
String json = MAPPER.writeValueAsString(record);
71+
String json = MAPPER.writeValueAsString(new SimpleRecord(123, "Bob"));
7172
final Object EXP = map("id", Integer.valueOf(123), "name", "Bob");
7273
assertEquals(EXP, MAPPER.readValue(json, Object.class));
7374
}
7475

7576
public void testDeserializeSimpleRecord() throws Exception {
76-
SimpleRecord value = MAPPER.readValue("{\"id\":123,\"name\":\"Bob\"}", SimpleRecord.class);
77-
assertEquals(new SimpleRecord(123, "Bob"), value);
77+
assertEquals(new SimpleRecord(123, "Bob"),
78+
MAPPER.readValue("{\"id\":123,\"name\":\"Bob\"}", SimpleRecord.class));
79+
}
80+
81+
public void testSerializeEmptyRecord() throws Exception {
82+
assertEquals("{}", MAPPER.writeValueAsString(new EmptyRecord()));
83+
}
84+
85+
public void testDeserializeEmptyRecord() throws Exception {
86+
assertEquals(new EmptyRecord(),
87+
MAPPER.readValue("{}", EmptyRecord.class));
7888
}
7989

8090
public void testSerializeRecordOfRecord() throws Exception {

0 commit comments

Comments
 (0)