Skip to content

Commit b4bc144

Browse files
author
haibojiang
committed
bugfix: jackson serializing can compatible with empty beans
1 parent 3586eb1 commit b4bc144

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

trpc-core/src/main/java/com/tencent/trpc/core/utils/JsonUtils.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import com.fasterxml.jackson.databind.DeserializationFeature;
1717
import com.fasterxml.jackson.databind.JavaType;
1818
import com.fasterxml.jackson.databind.ObjectMapper;
19+
import com.fasterxml.jackson.databind.SerializationFeature;
1920
import com.tencent.trpc.core.exception.ErrorCode;
2021
import com.tencent.trpc.core.exception.TRpcException;
2122
import com.tencent.trpc.core.logger.Logger;
@@ -39,6 +40,8 @@ public class JsonUtils {
3940
objectMapper.setSerializationInclusion(Include.NON_NULL);
4041
// Do not throw an error when deserializing if there are no corresponding properties
4142
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
43+
// Do not throw an error when serializing if there are no public fields
44+
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
4245
}
4346

4447
/**

trpc-core/src/test/java/com/tencent/trpc/core/utils/JsonUtilsTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ public class JsonUtilsTest {
3232
private static final String JSON = "{\"test\":123}";
3333
private static final String JSON_LIST = "[{\"test\":123},{\"test\":123}]";
3434
private static final String ERROR_JSON = "{\"test\":123,A}";
35+
private static final String EMPTY_JSON = "{}";
3536

3637
@Test
3738
public void testCopy() {
@@ -184,6 +185,12 @@ public void testConvertValue() {
184185
}
185186

186187

188+
@Test
189+
public void testEmptyBeanSerial() {
190+
TestEmptyBean testEmptyBean = new TestEmptyBean(10);
191+
Assert.assertEquals(EMPTY_JSON, JsonUtils.toJson(testEmptyBean));
192+
}
193+
187194
public static class TestObj {
188195

189196
private int testA;
@@ -232,4 +239,14 @@ public void setData(String data) {
232239
this.data = data;
233240
}
234241
}
242+
243+
public static class TestEmptyBean {
244+
245+
// without public getter method
246+
private int field;
247+
248+
public TestEmptyBean(int field) {
249+
this.field = field;
250+
}
251+
}
235252
}

0 commit comments

Comments
 (0)