moshi-lazy-adapters
moshi-lazy-adapters copied to clipboard
Wrapped adapter does not wrap the post payload in the given path when serializing
Wrapped adapter is extremely convenient when deserializing unnecessarily wrapped json responses without having to create wrapper classes.
But it doesn't seem to work when serializing POST
data.
Endpoint: POST api/{surveyId}/answers
Example Body:
{ //SurveyAnswerPayload.class
"answers": [
{ //SurveyAnswer.class
"questionId": "1",
"answer": "Foo"
}, {
"questionId": "2",
"answer": "Bar"
}
]
}
Trying to use Wrapped adapter to avoid creating a wrapper object SurveyAnswerPayload
like so:
public class SurveyAnswer {
@Json(name = "questionId")
public String questionId;
@Json(name = "answer")
public String answer;
}
public interface SurveyService{
@POST("surveys/{surveyId}/answers")
@Wrapped(path = {"answers"})
Call<Void> postAnswers(@Path("surveyId") String surveyId, @Body List<SurveyAnswer> answers);
}
Sadly this doesn't work. It serializes into [{"questionId":"1","answer":"A"},{"questionId":"2","answer":"B"}]
Wrapper class SurveyAnswerPaylod
is needed here to get it wrapped in a parent "{"answers":[{"questionId":"1","answer":"A"},{"questionId":"2","answer":"B"}]}
"
class SurveyAnswerPayload{
@Json(name = "answers")
public List<SurveyAnswer> answers;
}
Check out LazyAdaptersRetrofitTest.java
there's a service method that utilizes this.
Change SurveyService
to be:
public interface SurveyService{
@POST("surveys/{surveyId}/answers")
Call<Void> postAnswers(@Path("surveyId") String surveyId, @Wrapped(path = {"answers"}) @Body List<SurveyAnswer> answers);
}