使用Jackson(JSON)序列化 - 获取“未找到序列化程序”? [英] Serializing with Jackson (JSON) - getting "No serializer found"?
问题描述
我尝试使用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))
org.codehaus.jackson.map.JsonMappingException: No serializer found for class MyPackage.TestA and no properties discovered to create BeanSerializer (to avoid exception, disable 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);
有关相关配置选项的更多信息和详细信息,建议您查看 上的JavaDocs> ObjectMapper.setVisibility()
。
For more information and details on related configuration options, I recommend reviewing the JavaDocs on ObjectMapper.setVisibility()
.
这篇关于使用Jackson(JSON)序列化 - 获取“未找到序列化程序”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!