Home > Software engineering >  Mapping different HTTP JSON response using Jackson
Mapping different HTTP JSON response using Jackson

Time:03-04

I'm making a web server using Spring(Kotlin), and trying to map JSON response using Jackson. I need to send a request to other API server, so I decided to use OkHttp to send request. But, there is a problem that If the other API server responds with error like 4XX, Jackson couldn't map response because the response has different JSON structure.

Here's the code:

@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)
}

The class "Message" has a structure like this:

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
        }
    }
}

And, an error of other API server has a structure like this:

class Error {
    var errCode: String? = null
    var errMessage: String? = null
}

How can I map different JSON response?

CodePudding user response:

You should create two different Struct for the northbound API and the southbound API.

For the southbound API, add errCode and errMessage to SouthBoundMessage. Or check the HTTP status code if you can, then use a different Jackson mapper for Error Message.

Then convert SouthBoundMessage to NorthBoundMessage, which is your business logic.

Return NorthBoundMessage and corresponding HTTP code for northbound API consumers.

  • Related