java - Retrofit Dynamic ResponseBody -


i planning make 1 common service class use of retrofit,

@get call<responsebody> makegetrequest(@url string url);  @post call<responsebody> makepostrequest(@url string url, @body requestbody parameters); 

in code need pass (responsebody) dynamic json pojo class name , loginres

say example ,

call<loginres> // class dynamic 

i pass responsebody responsebody not know class wanted prefer.

why want because , after result

gson.fromjson(response, loginres.class); 

so, after getting result retrofit again need convert gson.fromjson.

so wanted pass dynamic response retrofit response according pojo class,

i know working fine when pass loginres instead of responsebody because told response need response in loginres.

so if pass

call<loginres> // if pass way working fine no need convert response can access properties loginres class directly.  

this example call web service.

call<responsebody> call = apiservice.makepostrequest("/buyer/loginapp", requestbody); 

this how call service.

let me know if unclear explanation of problem.

waiting response , suggestions on this.

thanks madhav

this bit tricky you'll need use custom retrofit converter factory custom gsonbuilder uses custom jsondeserializer.

furthermore should define interface (customresonse in example) customjsondeserializer used. not needed, otherwise deserializer gets used every request.

public class customconverterfactory {      public static gsonconverterfactory create() {         return gsonconverterfactory.create(creategsoncustomdeserializer());     }      public static gson creategsoncustomjsondeserializer() {         return new gsonbuilder()             .registertypeadapter(customresponse.class, new customjsondeserializer())             .serializenulls()             .create();     } } 

and deserializer:

public class customjsondeserializer implements jsondeserializer<customresponse> {  @override public customresponse deserialize(final jsonelement json, final type typeoft,         final jsondeserializationcontext context) throws jsonparseexception {     if (json.isjsonobject()) {         jsonobject jsonobject = json.getasjsonobject();          // here have distinguish class somehow         // maybe read json field response         if (jsonobject.has("name")) {             jsonelement classes = jsonobject.get("name");             ...             return context.deserialize(json, myname.class);         }         ...         // default fallback: deserialize fallback object         return context.deserialize(json, myfallback.class);     } else {         throw new illegalstateexception();     } } 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -