【问题标题】:Capture JSON from representation and return String value从表示中捕获 JSON 并返回字符串值
【发布时间】:2016-05-25 03:23:35
【问题描述】:

我有一个如下所示的工作网络服务,它将返回 JSON 格式的双精度值,例如{"PMC":17.34}

@Override
@Post("JSON")
public Representation post(Representation entity) throws ResourceException
{
    JsonObjectBuilder response = Json.createObjectBuilder();

    try {
        String json = entity.getText(); // Get JSON input from client
        Map<String, Object> map = JsonUtils.toMap(json); // Convert input into Map
        double result = matrix.calculatePMC(map); // Calculate PMC value
        response.add("PMC", result);
    } catch (IOException e) {
        LOGGER.error(this.getClass() + " - IOException - " + e);
        getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    }

    return new StringRepresentation(response.build().toString());       
}

现在,我想更改程序以仅返回双精度值,即17.34,因此我将程序修改为以下内容:

@Post
public double post(Response response)
{
    double result = 0;

    try {
        String json = response.getEntity().getText(); //Get JSON input from client
        Map<String, Object> map = JsonUtils.toMap(json); // Convert input into Map
        result = matrix.calculatePMC(map); // Calculate PMC value
    } catch (IOException e) {
        LOGGER.error(this.getClass() + " - IOException - " + e);
        getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
    }

    return result;      
}

当我运行它时,我得到一个415 Unsupported Media Type 错误。我错过了什么?

【问题讨论】:

  • 请将@Post public double post(Response response) 更改为@Post("json") public double postImpl(String json) 并告诉我们您得到了什么。
  • 感谢@AbhishekOza 为我指明了正确的方向!

标签: web-services rest jakarta-ee restlet


【解决方案1】:

误读程序要求,它应该返回一个字符串值(双精度)。以下是我的最终工作程序:

@Post
public String post(String json)
{
    double result = 0;
    Map<String, Object> map = JsonUtils.toMap(json); // Convert JSON input into Map
    result = matrix.calculatePMC(map); // Calculate PMC value

    return String.valueOf(result);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2015-10-03
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多