JAX-RS客户端的PUT / POST请求:无法访问正文中的实体(对象)

时间:2019-07-16 09:55:25

标签: java rest jax-rs

我使用如下所示的沼泽标准JAX-RS客户端代码(从https://www.baeldung.com/jersey-jax-rs-client借用 ):

Client client = ClientBuilder.newClient();       
Amount amount = new Amount("GBP", totalSavings);
       Response response = client.target(TRANSFER_TO_SAVINGS_GOAL_REST_URI)
                    .resolveTemplate("accountUid", accountUid)
                    .resolveTemplate("savingsGoalUid", savingsUid)
                    .request()
                    .header("Accept", "application/json")
                    .header("Authorization", "Bearer " + customerToken)
                    .put(Entity.json(amount));

现在,这失败了,就像返回400错误请求一样。

在接收端,发送的实体(amount)为空。知道为什么吗?

我正在检查调试器,并且该实体具有真实的值,但是如果我按如下所示构建测试@Post终点:

@PutMapping(value = "/account/{accountUid}/savings-goals/{savingsGoalUid}/add-money/{transferUid}")
public Response getUserHistory(String amount,
                               @PathVariable("accountUid") UUID accountUid,
                               @PathVariable("savingsGoalUid") UUID savingsGoalUid,
                               @PathVariable("transferUid") UUID transferUid) {
    log.info("Amount: " , amount);

    return null;
}

这确实确认金额为空。

请帮忙吗?

2 个答案:

答案 0 :(得分:1)

希望对某人有所帮助的答案是:

最后一点:

...
Entity.json(amount);

未为Amount生成所需的JSON结构。必填:

{
  "amount": {
    "currency": "GBP",
    "minorUnits": 1
  }
}

生成:

{ "currency": "GBP",
  "minorUnits": 1
}

为解决此问题,我在Amount类中添加了以下2个注释:

@JsonTypeName("amount")
@JsonTypeInfo(include = WRAPPER_OBJECT, use = NAME)
public class Amount {
    private String currency;
    private long minorUnits;
}

产生所需的JSON格式。

要检查请求中JSON的值,我使用了以下步骤:

response.readEntity(String.class)

amount打印了JSON字符串

答案 1 :(得分:0)

一方面,金额是一个对象,另一方面,金额是一个简单的字符串。您是否尝试过创建error: linking with `arm-linux-gnueabihf-gcc-with-link-search` failed: exit code: 1 | <omitted...> "/root/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/arm-unknown-linux-gnueabihf/lib/libcompiler_builtins-97e19be7db966560.rlib" "-Wl,-Bdynamic" "-lportaudio" "-lasound" "-lm" "-lpthread" "-lutil" "-lutil" "-ldl" "-lrt" "-lpthread" "-lgcc_s" "-lc" "-lm" "-lrt" "-lpthread" "-lutil" "-lutil" = note: /opt/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/../lib/gcc/arm-linux-gnueabihf/4.8.3/../../../../arm-linux-gnueabihf/bin/ld: warning: libjack.so.0, needed by /usr/lib/arm-linux-gnueabihf/libportaudio.so, not found (try using -rpath or -rpath-link) /usr/lib/arm-linux-gnueabihf/libportaudio.so: undefined reference to `jack_on_shutdown' /usr/lib/arm-linux-gnueabihf/libportaudio.so: undefined reference to `jack_port_name' /usr/lib/arm-linux-gnueabihf/libportaudio.so: undefined reference to `jack_connect' /usr/lib/arm-linux-gnueabihf/libportaudio.so: undefined reference to `jack_frame_time' /usr/lib/arm-linux-gnueabihf/libportaudio.so: undefined reference to `jack_port_by_name' etc. 类的getUserHistory方法?

然后您可以执行以下操作:

Amount

如果您希望接收json,那么我认为将完整的json对象映射到字符串将不起作用

希望这会有所帮助!