当我试图使用Jackson序列化一个非常简单的对象时,我得到了一个异常。错误:

jsonmappingexception:没有找到序列化器 类MyPackage。TestA和没有属性 发现以创建BeanSerializer(为避免异常,禁用 SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS))

下面是要序列化的简单类和代码。

有人能告诉我为什么我得到这个错误吗?

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();
}

当前回答

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:

myObjectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

有关相关配置选项的更多信息和详细信息,我建议查看ObjectMapper.setVisibility()上的JavaDocs。

其他回答

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:

myObjectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

有关相关配置选项的更多信息和详细信息,我建议查看ObjectMapper.setVisibility()上的JavaDocs。

对于Oracle Java应用程序,在ObjectMapper实例化之后添加这个:

mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

我只有getter,在添加setter之后,问题就解决了。

虽然我添加了getter和setter,但我得到了相同的错误。后来我发现了一个bug,这是由声纳的建议,我cgahnged的getter和setter作为保护,这是导致问题的原因。一旦我修复了,它就会像预期的那样工作。

如果忘记在返回状态中添加.build()方法,也会抛出此错误。

return Response.status(Status.OK);         // fails
return Response.status(Status.OK).build(); // works

我得到了以下错误没有build()方法:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class com.sun.jersey.core.spi.factory.ResponseBuilderImpl