【问题标题】:Groovy HTTP Builder: Catching invalid formatted JSON responseGroovy HTTP Builder:捕获无效的格式化 JSON 响应
【发布时间】:2016-08-11 14:34:48
【问题描述】:

您好,我正在使用 Groovy HTTPBuilder 进行类似这样的 POST 调用:

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

但是由于一个错误(我自己无法解决),REST 服务器返回一个格式不正确的 JSON,从而在我的应用程序尝试解析它时导致以下异常:

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

我对 groovy 闭包和 HTTPBuilder 还很陌生,但是有没有办法让应用程序在解析 JSON 之前检查它是否真的有效,如果是则返回 null?

【问题讨论】:

  • 不管有没有配置,都可以try/catch

标签: json groovy httpbuilder


【解决方案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
    }
}

【讨论】:

  • 谢谢解决了这个问题 :) 我绝对明白为什么这不是一个好主意..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多