2016-08-11 8 views
1

こんにちは私はこのような類似したPOSTの呼び出しにするためにGroovyのHTTPBuilderを使用しています:、原因(私は自分自身を解決することはできません)バグにただしGroovyのHTTPビルダー:キャッチ無効なフォーマットされたJSONレスポンス

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

をRESTをサーバーは正しくフォーマットされていないJSONを返します。

groovy.json.JsonException:現在の文字を判別できません。文字列、数値、配列などではありません。またはオブジェクト

私はfaiですGroovyのクロージャとHTTPBuilderの新機能ですが、は、JSONが解析する前に実際に有効かどうかをアプリケーションがチェックし、そうであればnullを返すようにする方法がありますか?

+0

かかわらず、設定がある場合、あなたは試す行うことができます/キャッチ – 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

関連する問題