Skip to content

Commit

Permalink
bugfix: jackson serializing can compatible with empty beans
Browse files Browse the repository at this point in the history
  • Loading branch information
haibojiang committed Nov 25, 2024
1 parent 3586eb1 commit b4bc144
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.tencent.trpc.core.exception.ErrorCode;
import com.tencent.trpc.core.exception.TRpcException;
import com.tencent.trpc.core.logger.Logger;
Expand All @@ -39,6 +40,8 @@ public class JsonUtils {
objectMapper.setSerializationInclusion(Include.NON_NULL);
// Do not throw an error when deserializing if there are no corresponding properties
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// Do not throw an error when serializing if there are no public fields
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public class JsonUtilsTest {
private static final String JSON = "{\"test\":123}";
private static final String JSON_LIST = "[{\"test\":123},{\"test\":123}]";
private static final String ERROR_JSON = "{\"test\":123,A}";
private static final String EMPTY_JSON = "{}";

@Test
public void testCopy() {
Expand Down Expand Up @@ -184,6 +185,12 @@ public void testConvertValue() {
}


@Test
public void testEmptyBeanSerial() {
TestEmptyBean testEmptyBean = new TestEmptyBean(10);
Assert.assertEquals(EMPTY_JSON, JsonUtils.toJson(testEmptyBean));
}

public static class TestObj {

private int testA;
Expand Down Expand Up @@ -232,4 +239,14 @@ public void setData(String data) {
this.data = data;
}
}

public static class TestEmptyBean {

// without public getter method
private int field;

public TestEmptyBean(int field) {
this.field = field;
}
}
}

0 comments on commit b4bc144

Please sign in to comment.