2016-08-11 90 views
1

嗨,我是使用Groovy HTTPBuilder作出类似这样的POST电话:Groovy的HTTP生成器:捕无效格式的JSON响应

http.request(POST, JSON) { req -> 
     body = [name:'testName', title:'testTitle'] 
     response.success = { resp, json -> 
      println resp.statusLine 
      println json 
     } 
    } 

然而,由于一个Bug(我解决不了我自己),其余服务器返回格式不正确的JSON,导致以下异常,当我的应用程序试图解析它时:

groovy.json.JsonException:无法确定当前字符,它不是字符串,数字,数组,或物体

我是fai rly是Groovy关闭和HTTPBuilder的新手,但有没有办法让应用程序检查JSON在解析之前是否确实有效,如果是的话返回null?

+0

无论是否有一个配置,你可以做的try/catch – cfrick

回答

1

我不确定这是个好主意,但可以提供自己的JSON解析器,这有助于原始请求。如果可以修复已知的问题,它还提供“修复”JSON的机会。

下面的示例。解析器本质上与HTTPBuilder uses相同的代码,但硬编码的UTF-8字符集除外。

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7') 

import groovy.json.* 

import groovyx.net.http.* 
import static groovyx.net.http.Method.* 
import static groovyx.net.http.ContentType.* 

def url = "http://localhost:5150/foobar/bogus.json" 

def http = new HTTPBuilder(url) 

http.parser."application/json" = { resp -> 
    println "tracer: custom parser" 
    def text = new InputStreamReader(resp.getEntity().getContent(), "UTF-8"); 
    def result = null 
    try { 
     result = new JsonSlurper().parse(text) 
    } catch (Exception ex) { 
     // one could potentially try to "fix" the JSON here if 
     // there is a known bug in the server 
     println "warn: custom parser caught exception" 
    } 

    return result 
} 

http.request(POST, JSON) { req -> 
    body = [name:'testName', title:'testTitle'] 
    response.success = { resp, json -> 
     println resp.statusLine 
     println json 
    } 
} 
+0

由于解决了这个问题:)我可以肯定明白为什么它不是一个好主意,但.. – SimonTheLeg