Skip to content

Retrofit template: return body string directly when failed to parse response body as JSON #1032

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 30, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,20 @@ package {{invokerPackage}};

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.lang.reflect.Type;

import retrofit.RestAdapter;
import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
import retrofit.converter.GsonConverter;
import retrofit.mime.TypedByteArray;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput;

public class ServiceGenerator {
// No need to instantiate this class.
Expand All @@ -15,9 +27,63 @@ public class ServiceGenerator {
.create();
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("{{basePath}}")
.setConverter(new GsonConverter(gson))
.setConverter(new GsonConverterWrapper(gson))
.build();

return adapter.create(serviceClass);
}
}

/**
* This wrapper is to take care of this case:
* when the deserialization fails due to JsonParseException and the
* expected type is String, then just return the body string.
*/
class GsonConverterWrapper implements Converter {
private GsonConverter converter;

public GsonConverterWrapper(Gson gson) {
converter = new GsonConverter(gson);
}

@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
byte[] bodyBytes = readInBytes(body);
TypedByteArray newBody = new TypedByteArray(body.mimeType(), bodyBytes);
try {
return converter.fromBody(newBody, type);
} catch (ConversionException e) {
if (e.getCause() instanceof JsonParseException && type.equals(String.class)) {
return new String(bodyBytes);
} else {
throw e;
}
}
}

@Override public TypedOutput toBody(Object object) {
return converter.toBody(object);
}

private byte[] readInBytes(TypedInput body) throws ConversionException {
InputStream in = null;
try {
in = body.in();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[0xFFFF];
for (int len; (len = in.read(buffer)) != -1;)
os.write(buffer, 0, len);
os.flush();
return os.toByteArray();
} catch (IOException e) {
throw new ConversionException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignored) {
}
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,20 @@

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.lang.reflect.Type;

import retrofit.RestAdapter;
import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
import retrofit.converter.GsonConverter;
import retrofit.mime.TypedByteArray;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput;

public class ServiceGenerator {
// No need to instantiate this class.
Expand All @@ -15,9 +27,63 @@ public static <S> S createService(Class<S> serviceClass) {
.create();
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("http://petstore.swagger.io/v2")
.setConverter(new GsonConverter(gson))
.setConverter(new GsonConverterWrapper(gson))
.build();

return adapter.create(serviceClass);
}
}

/**
* This wrapper is to take care of this case:
* when the deserialization fails due to JsonParseException and the
* expected type is String, then just return the body string.
*/
class GsonConverterWrapper implements Converter {
private GsonConverter converter;

public GsonConverterWrapper(Gson gson) {
converter = new GsonConverter(gson);
}

@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
byte[] bodyBytes = readInBytes(body);
TypedByteArray newBody = new TypedByteArray(body.mimeType(), bodyBytes);
try {
return converter.fromBody(newBody, type);
} catch (ConversionException e) {
if (e.getCause() instanceof JsonParseException && type.equals(String.class)) {
return new String(bodyBytes);
} else {
throw e;
}
}
}

@Override public TypedOutput toBody(Object object) {
return converter.toBody(object);
}

private byte[] readInBytes(TypedInput body) throws ConversionException {
InputStream in = null;
try {
in = body.in();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[0xFFFF];
for (int len; (len = in.read(buffer)) != -1;)
os.write(buffer, 0, len);
os.flush();
return os.toByteArray();
} catch (IOException e) {
throw new ConversionException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ignored) {
}
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,14 @@ Void updatePetWithForm(
/**
* Deletes a pet
*
* @param apiKey
* @param petId Pet id to delete
* @param apiKey
* @return Void
*/

@DELETE("/pet/{petId}")
Void deletePet(
@Header("api_key") String apiKey,@Path("petId") Long petId
@Path("petId") Long petId,@Header("api_key") String apiKey
);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ public class Pet {
**/
@ApiModelProperty(required = true, value = "")
@SerializedName("photoUrls")
private List<String> photoUrls = new ArrayList<String>() ;
private List<String> photoUrls = null;

/**
**/
@ApiModelProperty(value = "")
@SerializedName("tags")
private List<Tag> tags = new ArrayList<Tag>() ;
private List<Tag> tags = null;
public enum StatusEnum {
available, pending, sold,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public void testDeletePet() throws Exception {
api.addPet(pet);

Pet fetched = api.getPetById(pet.getId());
api.deletePet(null, fetched.getId());
api.deletePet(fetched.getId(), null);

try {
fetched = api.getPetById(fetched.getId());
Expand Down