Reputation: 3661
I have a question about Android development using Retrofit by Square.
Let's say I have a Response object which is actually a HashMap<String, String>
object.
Is there a way to get a HashMap
object from this Retrofit object?
Thanks!
Upvotes: 5
Views: 6160
Reputation: 1179
@Jake Wharton says: Gson will deserialize a Map without any configuration. So you really don't have to do any of this.
just specify a Map
as your Retrofit return type or Callback type.
Upvotes: 0
Reputation: 50578
Response
object contains various information about response returned from the server.
If you mean that response body is HashMap
you can either parse the body when success()
is called, or register type adapter when build your RestAdapter
and write deserializer that will parse and populate the HashMap
.
private RestAdapter getRestAdapter(){
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<HashMap<String, String>>(){}.getType(), new MyHashMapDeserializer());
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setClient(new OkClient());
builder.setLogLevel(RestAdapter.LogLevel.FULL);
builder.setExecutors(Executors.newCachedThreadPool(), new MainThreadExecutor());
builder.setConverter(new GsonConverter(gsonBuilder.create()));
builder.setEndpoint(API_END_POINT_URL);
return builder.build();
}
Then create new class (or inner class) that will implements JsonDeserializer<HashMap<String, String>>
and implement your deserialization logic.
Make sure you adapt K,V
types to your needs.
Upvotes: 2