使用Retrofit 2.0在体内发布请求JSON

问题描述

我想将JSON参数发送到API,而我实现的目标是这样的:

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

因此,基本上,我将使用“ v1”和“ v2”作为参数发送2个JSON对象。但是我想要实现的是像这样发送参数:

{"username" : "password"}

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

POJO类

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);
}

MainActivity类

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类中,我已经声明了“ v1”和“ v2”,所以不要发送它:

{"username" : "password"}

我正在发送:

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

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

解决方法

您可以直接在@Body中使用地图,并按如下所示访问地图的键和值:

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变量。