简体   繁体   中英

Java method Overloading with REST - org.codehaus.jackson.map.JsonMappingException

I have a REST service that has a POST endpoint. This POST endpoint needs to receive an object ( TravelRequisitionFormDTO ) as part of its body:

@POST
@Path("/request")
@ApiOperation(value="Request a trip. Submit the trip request.")
@ApiResponses({
        @ApiResponse(code=200, message="Success"),
        @ApiResponse(code=404, message="Not Found")
})
@Produces({ MediaType.APPLICATION_JSON })
public Response getSubmitTrip(@HeaderParam("Authorization") String token, @ApiParam(required = true) TravelRequisitionFormDTO travelRequisitionFormDTO, @Context HttpServletRequest request)  {
            ...
    }

So when I call the endpoint, I get the following error:

<p><b>message</b> <u>org.codehaus.jackson.map.JsonMappingException: Conflicting setter definitions for property
        &quot;contactMethods&quot;: utility.dataobjects.ContactObject#setContactMethods(1 params) vs
        utility.dataobjects.ContactObject#setContactMethods(1 params)</u></p>
<p><b>description</b> <u>The request sent by the client was syntactically incorrect
        (org.codehaus.jackson.map.JsonMappingException: Conflicting setter definitions for property
        &quot;contactMethods&quot;: utility.dataobjects.ContactObject#setContactMethods(1 params) vs
        utility.dataobjects.ContactObject#setContactMethods(1 params)).</u></p>

The reason for the error is because the TravelRequisitionFormDTO has a member variable (called ContactObject ) that has two methods that are overloaded. So when it tries to convert the JSON body to JAVA, I guess it does not know which overloaded method to use. I think it sees it as ambiguous.

public void setContactMethods(ArrayList list)

and

public void setContactMethods(String[] list)

I don't want to change ContactObject if possible, because it is used in a number of other places.

Question

Is there any way I can resolve this? ie so that the JSON body can be converted successfuly into the Java object?

you can keep single property accepting List. and your Contractobject can consume both Array & List.

You could annotate one setter with Jackson @JsonSetter annotation:

@JsonSetter
public void setContactMethods(ArrayList list)

Make sure that you use right package. In your case it would be org.codehaus.jackson.annotate.JsonSetter like you can see in the error message. It might happen that you have also com.fasterxml.jackson.annotation.JsonSetter in the classpath so you have to be careful not to mix it.

Alternatively you can use @JsonProperty instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM