问题描述
尝试使用 Jackson 序列化一个非常简单的对象时出现异常.错误:
I get the an exception when trying to serialize a very simple object using Jackson. The error:
org.codehaus.jackson.map.JsonMappingException: 找不到序列化程序类 MyPackage.TestA 并且没有属性发现创建 BeanSerializer(为避免异常,禁用SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
下面是要序列化的简单类和代码.
Below is the simple class and code to serialize.
谁能告诉我为什么我会收到这个错误?
Can anyone tell my why I get this error?
public class TestA {
String SomeString = "asd";
}
TestA testA = new TestA();
ObjectMapper om = new ObjectMapper();
try {
String testAString = om.writeValueAsString(testA); // error here!
TestA newTestA = om.readValue(testAString, TestA.class);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
推荐答案
如前所述,ObjectMapper
实例的默认配置是仅访问公共字段或具有公共 getter/setter 的属性.更改类定义以使字段公开或提供公共 getter/setter 的替代方法是指定(对基础 VisibilityChecker
)不同的属性可见性规则.Jackson 1.9 为此提供了 ObjectMapper.setVisibility()
方便的方法.对于原始问题中的示例,我可能会将其配置为
As already described, the default configuration of an ObjectMapper
instance is to only access properties that are public fields or have public getters/setters. An alternative to changing the class definition to make a field public or to provide a public getter/setter is to specify (to the underlying VisibilityChecker
) a different property visibility rule. Jackson 1.9 provides the ObjectMapper.setVisibility()
convenience method for doing so. For the example in the original question, I'd likely configure this as
myObjectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
对于杰克逊 >2.0:
For Jackson >2.0:
myObjectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
有关相关配置选项的更多信息和详细信息,我建议查看ObjectMapper.setVisibility()
上的 JavaDocs一>.
For more information and details on related configuration options, I recommend reviewing the JavaDocs on ObjectMapper.setVisibility()
.
这篇关于使用 Jackson (JSON) 进行序列化 - 获得“未找到序列化程序"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!