I have an API which is being extended to be consumed by another system. Pre-req's exist whereby each frontend has different expectations for one json field.
Example: The response field 'amount' must be either a String or an int, depending on which value I receive from downstream. So for some instances I will return a string value in the json, while in others I will return int.
Expected json outputs:
{
"amount": 21
}
or
{
"amount": "21"
}
I have done the following:
class Response {
@JsonProperty("amount")
private int amount;
@JsonProperty("amount")
private String amountString;
// Getters and setters
Hoping that I would be able to return either an int or String value for the json field 'amount' but I'm getting the following error:
com.fasterxml.jackson.databind.JsonMappingException: Conflicting getter definitions for property "amount"
Any help would be appreciated
CodePudding user response:
You can not do that. The element in your JSON is called amount, you can not bind it to 2 different variables.
You are getting this exception because the @JsonProperty("amount") is used on 2 seperate class fields.
It is best to create 2 different response:
Example:
class FrontEndResponse1 {
@JsonProperty("amount")
private int amount;
//getter/setter
}
class FrontEndResponse2 {
@JsonProperty("amount")
private String amount;
//getter/setter
}
CodePudding user response:
I think you can just return the string type and solve the problem on the javascript
CodePudding user response:
Yes, this won't work with typed return values.
Unless you're fine with providing 2 endpoints with different return types you could return a plain Map<String, Object> instead of Response:
public Map<String, Object> awkwardMethod(boolean wantString) {
Response response = new Response();
... // do business logic
return Map.of("amount", wantString ? String.value(response.amount) : response.amount);
}
To be clear: I'm not encouraging you to do this as you'll loose type information for the return value and introduce error prone manual mapping. I'm just providing a solution for a problem that should be fixed by providing a clear API and clients sticking to this API.
