Reputation: 9842
I am building an API, and when I send a request like this:
POST http://myserver.dev
{
"id": "1",
"string1": "hello",
"string2": "world"
}
everything works as expected testing this with curl
and Postman. However, using my Android code, the request fails:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("id", "1");
jsonObject.put("string1", "hello");
jsonObject.put("string2", "world");
}
catch (JSONException e)
{
e.printStackTrace();
}
String jsonString = jsonObject.toString();
And the server gives me this error:
JSON::ParserError (757: unexpected token at '"{\"id\":\"1\",\"string1\":\"hello\",\"string2\":\"world\"}"'):
It seems as though this jsonObject is not giving me the expected json string. Any ideas what's going on here?
The full HTTP request from logcat is here:
04-26 15:23:56.468 21013-21669/com.johncorser.s D/Retrofit﹕ ---> HTTP POST http://api.s.com/games
04-26 15:23:56.469 21013-21669/com.johncorser.s D/Retrofit﹕ X-Authorization: 10155399143045080
04-26 15:23:56.469 21013-21669/com.johncorser.s D/Retrofit﹕ Content-Type: application/json; charset=UTF-8
04-26 15:23:56.469 21013-21669/com.johncorser.s D/Retrofit﹕ Content-Length: 95
04-26 15:23:56.469 21013-21669/com.johncorser.s D/Retrofit﹕ {"nameValuePairs":{"id":"1","string1":"hello","string2":"world"}}
04-26 15:23:56.469 21013-21669/com.johncorser.s D/Retrofit﹕ ---> END HTTP (95-byte body)
And from the server logs:
2015-04-26T19:26:39.371386+00:00 app[web.1]: Parameters: {"_json"=>"{\"id\":\"1\",\"string1\":\"hello\",\"string2\":\"world\"}", "game"=>{}}
JSON::ParserError (757: unexpected token at '"{\"id\":\"1\",\"string1\":\"hello\",\"string2\":\"world\"}"'):
Upvotes: 1
Views: 94
Reputation: 9842
This ended up being a consequence of how Retrofit serializes objects before post.
I ended up switching from using a JSONObject
to a HashMap<String, String>
and not calling any .toString()
method, Retrofit took care of the rest.
Upvotes: 1