fge*_*fge 8 java serialization jackson json-deserialization
这是杰克逊2.2.x.
我有一个班级实施JsonSerializable; 有两种方法可以实现这个接口,serialize()和serializeWithType().
我想测试这个类的{de,}序列化,我可以serialize()轻松触发调用; 但是,不是serializeWithType().
[...]预计其他类型信息将包含在序列化中,以便进行反序列化.
我只是不明白这意味着什么......
如何设置测试环境以便调用此方法?请注意,要序列化的JSON可以是除object之外的任何类型(即boolean,number,string,array都是有效类型).
如果要使用多态,则使用此方法
public class A {
...
}
public class B extends A {
...
}
public class C extends A {
...
}
Run Code Online (Sandbox Code Playgroud)
如果序列化C的实例然后尝试反序列化生成的json,但只知道它的子类型为A:
final ObjectMapper objectMapper = new ObjectMapper();
final String json = objectMapper.writeValueAsString(new C());
final A deserialized = objectMapper.readValue(json, A.class);
Run Code Online (Sandbox Code Playgroud)
您需要在生成的JSON中存储某些内容以保留序列化对象的实际类型.
这可以启用或者使用@JsonTypeInfo,或通过调用您的类enableDefaultTyping上的ObjectMapper.
这是使用JUnit和Mockito的示例测试用例
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class SerializeWithTypeTest {
private JsonSerializable serializable = mock(JsonSerializable.class);
@Test
public void shouldCallSerializeWithType() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper().enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
objectMapper.writeValueAsString(serializable);
// make sure serializeWithType is called once
verify(serializable, times(1)).serializeWithType(any(), any(), any());
}
}
Run Code Online (Sandbox Code Playgroud)