我正在使用Spring(Kotlin)制作一个Web服务器,并尝试使用JacksonMapJSON响应。我需要向其他API服务器发送请求,因此我决定使用OkHttp发送请求。但是,存在一个问题,如果其他API服务器响应错误(如4XX),Jackson无法Map响应,因为响应具有不同的JSON结构。
下面是代码:
@PostMapping("/test")
fun test(@org.springframework.web.bind.annotation.RequestBody requestJSON: RequestJSON): Message {
val JSON: MediaType = "application/json; charset=utf-8".toMediaType()
val mapper = ObjectMapper()
val requestJSONString: String = mapper.writeValueAsString(requestJSON)
val client = OkHttpClient()
val body: RequestBody = requestJSONString.toRequestBody(JSON)
val request: Request = Request.Builder()
.header("clientid", "blahblah")
.header("secret", "blahblah")
.url("blahblah")
.post(body)
.build()
val response: Response = client.newCall(request).execute()
return mapper.readValue(response.body?.string(), Message::class.java)
}
类“Message”具有如下结构:
class Message {
var message = NestedMessage()
class NestedMessage {
@JsonProperty("@type")
var type: String? = null
@JsonProperty("@service")
var service: String? = null
@JsonProperty("@version")
var version: String? = null
@JsonProperty("result")
var resultObject = Result()
class Result {
var srcLangType: String? = null
var tarLangType: String? = null
var translatedText: String? = null
var engineType: String? = null
var pivot: String? = null
var dict: String? = null
var tarDict: String? = null
}
}
}
并且,其他API服务器的错误具有这样的结构:
class Error {
var errCode: String? = null
var errMessage: String? = null
}
如何Map不同的JSON响应?
1条答案
按热度按时间b4wnujal1#
您应该为北向API和南向API创建两个不同的Struct。
对于南向API,将
errCode
和errMessage
添加到SouthBoundMessage。或者检查HTTP状态代码(如果可以),然后对错误消息使用不同的JacksonMap器。然后将SouthBoundMessage转换为NorthBoundMessage,这是您的业务逻辑。
返回NorthBoundMessage和北向API使用者对应HTTP代码