Skip to content

Instantly share code, notes, and snippets.

@Komarev
Last active May 4, 2016 10:45
Show Gist options
  • Save Komarev/a640fafbade55610ea41882b5ff2a47f to your computer and use it in GitHub Desktop.
Save Komarev/a640fafbade55610ea41882b5ff2a47f to your computer and use it in GitHub Desktop.
@Multipart
@PUT("/users/me")
Observable<UserResponse> updateUser(
@PartMap Map<String, Object> userData,
@Part("user[avatar]") TypedFile avatar
);
mApi.updateUser(request.getUser().getDataAsMap(null, null), request.getAvatar())
.compose(RxUtils.applySchedulersAndRetry())
package com.bookjane.models;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* Created by rkom on 19.04.16.
*/
public abstract class BasePartMap implements Reflectable {
private final static String MAP_POSTFIX = "]";
private final String mMapPrefix = getFieldMapPrefix();
@NonNull
public abstract String getFieldMapPrefix();
@Override
public Map<String, Object> getDataAsMap(@Nullable String parentPrefix,
@Nullable String parentPostfix) {
final String prefix = parentPrefix == null ? mMapPrefix : parentPrefix + mMapPrefix;
final String postfix = parentPostfix == null ? MAP_POSTFIX : parentPostfix + MAP_POSTFIX;
Field[] fields = this.getClass().getDeclaredFields();
Map<String, Object> map = new HashMap<>();
Object value;
SerializedName serialName;
for (Field field : fields) {
value = getFieldValue(field);
if (value != null) {
if (value instanceof Reflectable) {
map.putAll(((Reflectable) value).getDataAsMap(prefix, postfix));
continue;
}
serialName = field.getAnnotation(SerializedName.class);
if (serialName != null) {
map.put(prefix + serialName.value() + postfix, getFieldValue(field));
}
}
}
return map;
}
@Nullable
private Object getFieldValue(@NonNull Field field) {
try {
field.setAccessible(true);
if (field.getType().isEnum()) {
return field.get(this) == null ? null : field.get(this).toString();
} else {
return field.get(this);
}
} catch (IllegalAccessException e) {
return null;
}
}
}
public class User extends BasePartMap implements Parcelable {
private final static String MAP_PREFIX = "user[";
private final static int INT_NULL_FLAG = -1; // for Integer vars
@NonNull
@Override
public String getFieldMapPrefix() {
return MAP_PREFIX;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment