Grails RestBuilder发送奇怪的JSON

时间:2015-12-21 18:40:23

标签: json grails

我最近将我的项目的grails版本从2.3.6升级到2.5.0,以便使用符合Java 8的版本。我升级了很多插件版本以便与之配合使用升级的Grails版本。然而,RestBuilder表现得很时髦。它不是发送之前的常规JSON对象,而是将其包装在实际对象中(即{"target": {"var1":"value", "var2":"value"}, "prettyPrint": true})。

以下是我的依赖项:

    plugins {
    //runtime ":hibernate4:4.3.1.2"
    runtime ":hibernate:3.6.10.14"
    runtime ":resources:1.2.14"
    runtime ":database-migration:1.4.0"
    runtime ":httplogger:1.1"

    // Uncomment these (or add new ones) to enable additional resources capabilities
    //runtime ":zipped-resources:1.0"
    //runtime ":cached-resources:1.0"
    //runtime ":yui-minify-resources:0.1.5"

    build ":tomcat:7.0.52.1"

    compile ":spring-security-core:2.0-RC5"
    compile ":rest-client-builder:2.1.1"
}

这是代码:

def createCustomer(Customer customer, String customerId) {

    def enrollmentResponse = new CustomerEnrollmentResponse()
    def customerJson = customer as JSON
    def partnerKey = springSecurityService.getCurrentUser().partnerKey
    def baseUrl = grailsApplication.config.rest.baseUrl
    String url = "${baseUrl}${customerApiContextUrl}${partnerKey}/${customerId}"
    def resp = new RestBuilder().post(url) {
        contentType: "application/json"
        json: customerJson
    }
    enrollmentResponse.responseCode = resp.status
    if (enrollmentResponse.responseCode != 200) {
        enrollmentResponse.error = new APIError(resp.json)
    }
    return enrollmentResponse
}

3 个答案:

答案 0 :(得分:0)

不要使用" AS JSON"

改为使用

JsonBuilder json = new groovy.json.JsonBuilder(data)

json.toString()

这将为您提供准确的JSON值

答案 1 :(得分:0)

我已经添加了以下依赖项来构建配置,它对我有用

compile 'com.fasterxml.jackson.core:jackson-core:2.7.0'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.0'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.0'

答案 2 :(得分:-2)

默认的groovy json库存在一些问题。

如果你是我,我会使用杰克逊图书馆,这是最好的json图书馆。

的问候。