Reputation: 159
My code is working and its all good but what bothers me is that for every single response i have two classes.
This is how json looks like, there is a main object that have response object that always different.
object{
...
...
response{
...
...
}
}
Here the class with properties, so when there is auth operation api call i get an object and inside there is another response which will present the information mentioned below(accountID,authToken)
public class AuthResponse implements IResponse {
@JsonProperty
private String accountID;
@JsonProperty
private String authToken;
// IResponse just have a validation method
}
Here is a wrapper with AuthResponse that is called response so that jackson can locate it
public class NowOSAuthResponse extends NowOSResponse {
@JsonProperty
private AuthResponse response;
//can be replaced with @Getter
@Override
public IResponse getResponse() {
return response;
}
}
And finally here the main object that contain abstract interface so that every response has its own return object
public abstract class NowOSResponse {
@JsonProperty
private String version;
@JsonProperty
private String operation;
@JsonProperty
private String status;
public abstract IResponse getResponse();
So i wanted to know if there is a way how to give back the response object without create two classes. Thank you in advance
Upvotes: 0
Views: 226
Reputation: 1271
Maybe this code can helps you:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = mapper.createObjectNode();
root.putPOJO("response", Map.of("accountID", "id", "authToken", "token"));
root.put("version", "v1");
mapper.writer().writeValue(bos, root);
System.out.println(new String(bos.toByteArray(), StandardCharsets.UTF_8));
or
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = mapper.createObjectNode();
var response = Map.of("response", Map.of("accountID", "id", "authToken", "token"), "version", "v1");
mapper.writer().writeValue(bos, response);
System.out.println(new String(bos.toByteArray(), StandardCharsets.UTF_8));
Output: {"response":{"authToken":"token","accountID":"id"},"version":"v1"}
Upvotes: 1