Grails:使用 Jackson 时出现异常 API

Grails : getting exception while using Jackson API

使用 Jackson api.See 附加图片时出现以下异常。

class BlogSwiftJSONUtil {

static String parseToJSON(Object object){
        ObjectMapper objectMapper = new ObjectMapper()
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object)
    }
 }

下面的行我已经用于解析所有操作的输出 json。

render contentType: 'application/json', text:BlogSwiftJSONUtil.parseToJSON(listAllResources(params))

在BuildConfig.groovy中添加的jackson库如下:

dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
        // runtime 'mysql:mysql-connector-java:5.1.29'
        // runtime 'org.postgresql:postgresql:9.3-1101-jdbc41'
        test "org.grails:grails-datastore-test-support:1.0.2-grails-2.4"
        runtime 'com.fasterxml.jackson.core:jackson-core:2.0.4'
        runtime 'com.fasterxml.jackson.core:jackson-databind:2.0.4'
        runtime 'com.fasterxml.jackson.core:jackson-annotations:2.0.4'
    }

任何人为什么我得到这个例外。

以下是我的一些发现:

  1. 如果我像 object.properties 那样传递地图而不是对象本身,它就可以工作。
  2. 它似乎也在尝试序列化验证错误。

任何帮助都是值得的。

如果我可以分享任何其他详细信息,请告诉我。

谢谢!

为了让 jackson 整理您的响应,您需要一个具有 public getter/setter 私有字段的 bean,或者定义一个具有 public 可见性的字段。从您粘贴的屏幕截图来看,您的 api 调用似乎以某种方式失败,该调用重定向到 spring 以处理 jackson 无法序列化的异常。

您需要通过添加以下内容来解决这个问题:

objectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);

因为您将它用于 rest-api 并且很可能会序列化域、枚举和一些自定义 read-only pojo。此问题是因为未能序列化注入域的验证错误。您可以自定义域以选择用于序列​​化和反序列化的字段。

参见 this

为了更加灵活,请手动添加您自己的序列化器并给出您自己的定义,如下所示:

下面是添加自定义序列化器的方法

import com.blog.swift.marshaller.JacksonSerializer
import com.fasterxml.jackson.databind.Module
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule

class JSONUtil{
    static String parsetoJSON(Object object){
        ObjectMapper objectMapper = new ObjectMapper()

        Module testModule = new SimpleModule()
        testModule.addSerializer(new JacksonSerializer(object.getClass())); 
        objectMapper.registerModule(testModule)
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object)
        }
    }

下面是一个示例自定义序列化程序。

class JacksonSerializer extends StdSerializer{
    protected BSJacksonSerializer(Class t) {
        super(t)
    }

    @Override
    void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonGenerationException {
            jsonGenerator.writeStartObject()

            jsonGenerator.writeStringField("test","test")
            jsonGenerator.writeEndObject()
    }
}

StdSerializer 是一个抽象 class,它提供基本实现以帮助利用对自定义序列化逻辑的关注,而不是异常处理和任何其他事情。

希望对您有所帮助!