Grails:使用Jackson API时遇到异常

时间:2016-01-02 14:28:25

标签: java json grails jackson grails-2.5

使用Jackson api时获取以下异常。请参阅附件图片。

enter image description here

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. 似乎它也试图序列化验证错误。
  3. 任何帮助都是值得的。

    如果我可以分享任何其他详细信息,请与我们联系。

    谢谢!

2 个答案:

答案 0 :(得分:2)

为了让杰克逊能够对您的回复进行编组,您需要一个具有公共getter / setter的私有字段的bean,或者定义具有公共可见性的字段。从您粘贴的屏幕截图中,似乎您的api调用失败,重定向到spring以处理jackson无法序列化的异常。

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

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

答案 1 :(得分:0)

当你将它用于rest-api时,很可能会将域名,枚举和一些自定义的只读pojos序列化。此问题是由于序列化注入域的验证错误失败。您可以自定义域以选择序列化和反序列化的字段。

请参阅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 是一个抽象类,它提供了基本实现,有助于将重点放在自定义序列化逻辑上,而不是异常处理和任何其他事情。

希望它有所帮助!

相关问题