Reputation: 390
I want to send a JSON parameter to an API, and what I have achieved was like so :
{"v1" : "username", "v2" : "password"}
So basically I am sending 2 JSON object with "v1" and "v2" as the parameter. But what I wanted to achieve is sending the parameter like so :
{"username" : "password"}
I couldn't figure out how to do this. Here is my code for now :
POJO Class
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 Interface
public interface JsonPlaceHolderApi {
@POST("ratec")
Call<Post> createPost(@Body Post post);
}
MainActivity Class
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());
}
});
}
As you can see, this is the parameter that I am sending :
final Post post = new Post("name", "password");
Call<Post> call = jsonPlaceHolderApi.createPost(post);
And in the POJO class, I have declared "v1" and "v2", so instead of sending this :
{"username" : "password"}
I am sending this :
{"v1" : "username", "v2" : "password"}
I appreciate your help and suggestions. Thanks!
Upvotes: 0
Views: 234
Reputation: 63
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;
}
}
use JsonProperty
to customize the json variable to the way you need.
Upvotes: 0
Reputation: 777
You can directly use the map in the @Body and access the key and value of the map as below:
public interface JsonPlaceHolderApi {
@POST("ratec")
Call<Post> createPost(@Body Map<String,String> post);
}
Upvotes: 1