Skip to content

Instantly share code, notes, and snippets.

@samskiter
Last active August 29, 2015 14:14
Show Gist options
  • Save samskiter/822c78795f46df2571f9 to your computer and use it in GitHub Desktop.
Save samskiter/822c78795f46df2571f9 to your computer and use it in GitHub Desktop.
Url encode requests from GSON objects :)
package uk.co.airsource.android.authtest;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Set;
import retrofit.converter.GsonConverter;
import retrofit.mime.FormUrlEncodedTypedOutput;
import retrofit.mime.TypedOutput;
/**
* Created by sduke on 03/02/2015.
*/
public class GsonConverterUrlEncodedRequest extends GsonConverter
{
private final Gson gson;
private String charset;
/**
* Create an instance using the supplied {@link com.google.gson.Gson} object for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public GsonConverterUrlEncodedRequest(Gson gson) {
this(gson, "UTF-8");
}
/**
* Create an instance using the supplied {@link Gson} object for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use the specified charset.
*/
public GsonConverterUrlEncodedRequest(Gson gson, String charset) {
super(gson, charset);
this.gson = gson;
this.charset = charset;
}
@Override public TypedOutput toBody(Object object) {
try {
Set<Map.Entry<String, JsonElement>> fieldSet = gson.toJsonTree(object).getAsJsonObject().entrySet();
FormUrlEncodedTypedOutput formUrlEncodedTypedOutput = new FormUrlEncodedTypedOutput();
for (Map.Entry<String, JsonElement> entry : fieldSet)
{
if (!entry.getValue().isJsonPrimitive())
{
throw new UnsupportedEncodingException(
"GSON to URL encoding only supports shallow (depth=1) objects. Key: "
+ entry.getKey() + " contains a non-primitive object!");
}
String valueString = entry.getValue().getAsJsonPrimitive().getAsString();
formUrlEncodedTypedOutput.addField(entry.getKey(), valueString);
}
return formUrlEncodedTypedOutput;
} catch (UnsupportedEncodingException | IllegalStateException e) {
throw new AssertionError(e);
}
}
}
@pengrad
Copy link

pengrad commented Aug 3, 2015

Thanks for useful tip!
Maybe it's better to serialize not primitives as Json instead of throw Exception:
String valueString = entry.getValue().toString();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment