简体   繁体   中英

Complex object as a queryparameter in in java rest application

I need to be able to query a resource with a filter with many parameters (all optionals)

my url specification is something like this :

GET http://something/version/resource?f={"param1":"1","param2":"something else", "param3":"tomato"

I tried two approaches:

  1. @XmlRootElement so I created a class filter and annotated it with the @XmlRootElement but the parameters are not parsed into my class.
@XmlRootElement    
MyClassFilter{
   String param1;
   String param2;
   ..........

}
  1. @BeanParam so I removed the @XmlRootElement annotation and I put a @QueryParam annotation for every field in the class and in the resource method I put the @BeanParam one.
MyClassFilter{
   @QueryParam("param1")
   String param1;
   @QueryParam("param2")
   String param2;
   ..........

}   

I get null objects with both methods. Could someone point me to the right direction? I usually consume the services so I don't have much experience on the server side.

I solved my problem, in my get method I receive the filter as a string:

@QueryParam(value = "f") String f

and I parse it using the ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
EntityFilter filter = mapper.readValue(f, EntityFilter.class);

You can use ParamConverterProvider .

@Provider
public class JSONParamConverterProvider implements ParamConverterProvider {

    @Override
    public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
        if(rawType.equals(MyObject.class)){
            return (ParamConverter<T>) new JSONParamConverter();
        }
        return null;
    }
}

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