I am using Retrofit to call APIs. I am sending a post request to API but in the callback I am getting empty JSON like this {}.
Below is the code for RetrofitService<
After waiting for the best response I thought of answering my own question. This is how I resolved my problem.
I changed the converter of RestAdapter of RetrofitService and created my own Converter. Below is my StringConverter
static class StringConverter implements Converter {
@Override
public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
String text = null;
try {
text = fromStream(typedInput.in());
} catch (IOException ignored) {/*NOP*/ }
return text;
}
@Override
public TypedOutput toBody(Object o) {
return null;
}
public static String fromStream(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}
}
Then I set this converter to the RestAdapter in the Application class.
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.setConverter(new StringConverter())
.build();
mRetrofitService = restAdapter.create(RetrofitService.class);
Now whenever I use Retrofit, I get the response in String. Then I converted that String JSONObject.
RetrofitService mRetrofitService = app.getRetrofitService();
mRetrofitService.getUser(user, new Callback() {
@Override
public void success(String result, Response arg1) {
System.out.println("success, result: " + result);
JSONObject jsonObject = new JSONObject(result);
}
@Override
public void failure(RetrofitError error) {
System.out.println("failure, error: " + error);
}
});
Hence, I got the result in JSON form. Then I parsed this JSON as required.