Manually Parse Part Of A Response When Using Retrofit
I'm working with a REST API that returns a JSON document that starts as follows and includes a 'collection' of items with string IDs like 'ABC'. Note the 'routes' field, which cont
Solution 1:
It turns out that Retrofit's use of Gson by default makes it fairly easy to add a custom deserialiser to handle the portion of the JSON document that was the problem.
RestAdapterrestAdapter=newRestAdapter.Builder()
.setEndpoint(ApiDefinition.BASE_URL)
.setConverter(getGsonConverter())
.build();
public Converter getGsonConverter() {
Gsongson=newGsonBuilder()
.registerTypeAdapter(RouteList.class, newRouteTypeAdapter())
.create();
returnnewGsonConverter(gson);
}
publicclassRouteTypeAdapterimplementsJsonDeserializer<RouteList> {
@Overridepublic RouteList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)throws JsonParseException {
Gsongson=newGson();
RouteListrouteList=newRouteList();
JsonObjectjsonObject= json.getAsJsonObject();
for (Map.Entry<String,JsonElement> elementJson : jsonObject.entrySet()){
RouteListwardsRoutes= gson.fromJson(elementJson.getValue().getAsJsonArray(), RouteList.class);
routeList.addAll(wardsRoutes);
}
return routeList;
}
}
Solution 2:
After calling RestService, don't use Model Name as argument, you have to use Default Response
class from retrofit library.
RestService Method
@FormUrlEncoded@POST(GlobalVariables.LOGIN_URL)
void Login(@Field("email") String key, @Field("password") String value, Callback<Response> callback);
Calling method in Activity
getService().Login(email, password, newMyCallback<Response>(context, true, null)
{
@Overridepublicvoidfailure(RetrofitError arg0)
{
// TODO Auto-generated method stub
UtilitySingleton.dismissDialog((BaseActivity<?>) context);
System.out.println(arg0.getResponse());
}
@Overridepublicvoidsuccess(Response arg0, Response arg1)
{
Stringresult=null;
StringBuildersb=null;
InputStreamis=null;
try
{
is = arg1.getBody().in();
BufferedReaderreader=newBufferedReader(newInputStreamReader(is));
sb = newStringBuilder();
Stringline=null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
result = sb.toString();
System.out.println("Result :: " + result);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
Post a Comment for "Manually Parse Part Of A Response When Using Retrofit"