You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jersey接口如何根据Accept类型返回纯文本或JSON格式服务器时间

解决JAX-RS端点根据Accept头返回纯文本或JSON的问题

嗨,我明白你的困惑啦!当前你的代码不管请求的Accept类型是什么,都直接返回一个字符串——这在Accept是text/plain时没问题,但当Accept是application/json时,返回的裸字符串并不符合标准JSON格式(标准JSON应该是对象或数组结构)。下面给你两种靠谱的解决方案:

方案一:手动根据Accept头构建响应(简单直接)

你可以通过@Context注入请求对象,获取Accept头后动态生成对应格式的响应,同时注意用线程安全的日期格式化工具替代SimpleDateFormat(它线程不安全,多请求场景容易出问题):

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@GET 
@Produces({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) 
public Response getDateTime(@Context HttpServletRequest request) { 
    // 线程安全的日期格式化工具
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String currentDateTime = LocalDateTime.now().format(formatter); 
    
    String acceptHeader = request.getHeader("Accept"); 
    
    // 兼容Accept头包含多个类型的情况,比如"application/json,text/plain"
    if (acceptHeader != null && acceptHeader.contains(MediaType.APPLICATION_JSON)) { 
        // 构建标准JSON对象,避免裸字符串不符合规范的问题
        String jsonResponse = String.format("{\"currentDateTime\": \"%s\"}", currentDateTime); 
        return Response.ok(jsonResponse, MediaType.APPLICATION_JSON).build(); 
    } else { 
        // 返回纯文本格式
        return Response.ok(currentDateTime, MediaType.TEXT_PLAIN).build(); 
    } 
}

方案二:使用POJO+序列化库(更规范,适合复杂场景)

如果后续可能扩展返回字段,推荐定义一个POJO类,用Jackson等序列化库自动处理JSON转换,同时通过重写toString()处理纯文本输出:

第一步:定义POJO类

public class DateTimeResponse {
    private String currentDateTime;

    public DateTimeResponse(String currentDateTime) {
        this.currentDateTime = currentDateTime;
    }

    // 序列化库需要getter来读取字段
    public String getCurrentDateTime() {
        return currentDateTime;
    }

    public void setCurrentDateTime(String currentDateTime) {
        this.currentDateTime = currentDateTime;
    }

    // 纯文本输出时会调用这个方法
    @Override
    public String toString() {
        return currentDateTime;
    }
}

第二步:修改端点方法

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@GET 
@Produces({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON }) 
public Object getDateTime() { 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String currentDateTime = LocalDateTime.now().format(formatter); 
    DateTimeResponse response = new DateTimeResponse(currentDateTime);
    
    // JAX-RS会根据Accept头自动选择:JSON时序列化POJO,纯文本时调用toString()
    return response;
}

注意:确保你的项目中已经引入了Jackson JAX-RS依赖(比如jackson-jaxrs-json-provider),这样JAX-RS才能自动将POJO序列化为JSON。

内容的提问来源于stack exchange,提问作者marcusds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:38:54