编写代码 ServletRequestAttributes 响应json数据
时间: 2024-01-12 17:05:24 浏览: 81
ASP 处理JSON数据的实现代码
好的,您想知道如何在Java中使用ServletRequestAttributes来响应JSON数据,正确吗?
首先,您需要导入以下依赖项:
```
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
```
然后,您可以使用以下代码片段:
```
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class JsonUtil {
public static void writeJson(Object object) throws IOException {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = attributes.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
ObjectMapper mapper = new ObjectMapper();
out.write(mapper.writeValueAsString(object));
out.flush();
out.close();
}
}
```
这个实用程序类将ServletRequestAttributes转换为HttpServletResponse对象,并使用ObjectMapper将对象转换为JSON格式。最后,将响应输出到输出流中。
希望这可以解决您的问题!
阅读全文