Created
July 18, 2017 15:06
-
-
Save imasahiro/16cfaaceb85823414d06cb96be6bab4b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.linecorp.armeria.server.annotation; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.linecorp.armeria.common.DefaultHttpResponse; | |
import com.linecorp.armeria.common.HttpData; | |
import com.linecorp.armeria.common.HttpHeaderNames; | |
import com.linecorp.armeria.common.HttpHeaders; | |
import com.linecorp.armeria.common.HttpResponse; | |
import com.linecorp.armeria.common.HttpStatus; | |
/** | |
* Converts given object into {@link HttpResponse} using {@link ObjectMapper}. | |
*/ | |
public final class JacksonResponseConverter implements ResponseConverter { | |
/** | |
* Create a {@link JacksonResponseConverter} instance. | |
*/ | |
public static JacksonResponseConverter create(ObjectMapper objectMapper) { | |
return new JacksonResponseConverter(objectMapper); | |
} | |
private final ObjectMapper objectMapper; | |
private JacksonResponseConverter(ObjectMapper objectMapper) { | |
this.objectMapper = objectMapper; | |
} | |
@Override | |
public HttpResponse convert(Object resObj) throws Exception { | |
final DefaultHttpResponse res = new DefaultHttpResponse(); | |
final HttpData data = HttpData.of(objectMapper.writeValueAsBytes(resObj)); | |
HttpHeaders headers = HttpHeaders.of(HttpStatus.OK) | |
.setInt(HttpHeaderNames.CONTENT_LENGTH, data.length()); | |
res.write(headers); | |
res.write(data); | |
res.close(); | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment