我想发布带有车身改装的请求,其中的支架还有另一个支架
期望正文请求:{"attributes":{"data":"FOOBAR"},"deviceId":171,"type":"custom"}

我尝试使用反斜杠,但总是收到一个错误的请求。

Activity.java

StringBuilder stringBuilder = new StringBuilder("{\"data\":\"");
                                stringBuilder.append(commandInput.getText());
                                stringBuilder.append("\"}");

                                Tasker task = new Tasker(idUnit, "custom", stringBuilder.toString());
                                Call<Tasker> call2 = mApiService.postCommand(task);
                                call2.enqueue(new Callback<Tasker>() {
                                    @Override
                                    public void onResponse(Call<Tasker> call, Response<Tasker> response) {
                                        Toast.makeText(CommandActivity.this, getString(R.string.command_sent), Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onFailure(Call<Tasker> call, Throwable t) {
                                        Toast.makeText(CommandActivity.this, getString(R.string.command_failed), Toast.LENGTH_SHORT).show();
                                    }
                                });


Tasker.java

public class Tasker {
    private long deviceId;
    private String type;
    private String attributes;

    public Tasker(long deviceId, String type, String attributes) {
        this.deviceId = deviceId;
        this.type = type;
        this.attributes = attributes;
    }
}


预期结果有效载荷:

{"attributes":{"data":"FOOBAR"},"deviceId":171,"type":"custom"}


实际输出有效载荷:

{"attributes":"{\"data\":\"FOOBAR\"}","deviceId":171,"type":"custom"}

最佳答案

您需要一些类或Map对象来保存属性,而不是String attributes

另外,尝试使用JsonObject类,而不只是使用StringBuilder

07-25 21:34