Post 使用 Retrofit 2.0 在正文中请求 JSON

Post request JSON in body with Retrofit 2.0

我想将一个 JSON 参数发送到一个 API,我得到的结果是这样的:

{"v1" : "username", "v2" : "password"}

所以基本上我发送了 2 个 JSON 对象,其中“v1”和“v2”作为参数。但是我想要实现的是像这样发送参数:

{"username" : "password"}

我不知道该怎么做。这是我现在的代码:

POJOClass

class Post {

    private String v1;
    private String v2;
    private PostSuccess SUCCESS;

    public Post(String name, String password) {
        this.v1 = name;
        this.v2 = password;
    }
}

class PostSuccess {
    @SerializedName("200")
    private String resp;
    private String result;

    public String getResp() {
        return resp;
    }

    public String getResult() {
        return result;
    }
}

POST 界面

public interface JsonPlaceHolderApi {
    @POST("ratec")
    Call<Post> createPost(@Body Post post);
}

MainActivityClass

private void createPost() {
        final Post post = new Post("anthony", "21.000008", "72", "2");
        Call<Post> call = jsonPlaceHolderApi.createPost(post);

        call.enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {
                if (!response.isSuccessful()) {
                    textViewResult.setText("Code: " + response.code());
                    return;
                }    

                Post postResponse = response.body();
                String content = "";
                content += "Code : " + response.code() + "\n";
                textViewResult.setText(content);

            }
            @Override
            public void onFailure(Call<Post> call, Throwable t) {
                textViewResult.setText(t.getMessage());
            }
        });
    }

如您所见,这是我发送的参数:

final Post post = new Post("name", "password");
    Call<Post> call = jsonPlaceHolderApi.createPost(post);

并且在 POJO class 中,我已经声明了“v1”和“v2”,所以没有发送这个:

{"username" : "password"}

我正在发送这个:

{"v1" : "username", "v2" : "password"}

感谢您的帮助和建议。谢谢!

可以直接在@Body中使用map,访问map的key和value如下:

public interface JsonPlaceHolderApi {
    @POST("ratec")
    Call<Post> createPost(@Body Map<String,String> post);
}
class Post {
    @JsonProperty("username")
    private String v1;
    @JsonProperty("password")
    private String v2;
    private PostSuccess SUCCESS;

    public Post(String name, String password) {
        this.v1 = name;
        this.v2 = password;
    }
}

使用 JsonProperty 根据需要自定义 json 变量。