Issue
I have the following code:
ApolloRequestObj obj = ApolloRequestObj.builder()
.api_key("3434")
.domains(List.of("test"))
.build();
// how to send the object as a request body?
RequestBody requestBody = RequestBody.create(
MediaType.parse("application/json"), json);
Request request = new Request.Builder()
.url(".......")
.post(requestBody)
.header("Content-Type", "application/json")
.header("Cache-Control", "no-cache")
.build();
The object for request:
@Getter
@Setter
@Builder
private class ApolloRequestObj {
public String api_key;
public List < String > domains;
}
When I initialize the Object with some data I want to send it with payload data to a remote host. Do you know how I can send the object?
Solution
If your goal is to take a POJO and serialize to Json, you can configure an ObjectMapper from Jackson to do this for you.
Here is a short example,
ObjectMapper objectMapper = new ObjectMapper();
var jsonString = objectMapper.writeValueToString(obj);
RequestBody requestBody = RequestBody.create(
MediaType.parse("application/json"), jsonString);
// rest of code here.
You'll need to grab the Jackson library depending on what dependency management framework you are using.
If you need escaped Json you can accomplish this by a simple string replace to add escaped quotes.
Answered By - abc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.