I need to parse a response from the Flickr API.
http://api.flickr.com/services/feeds/photos_public.gne?tagmode=any&format=json
which returns a response in jsonFlickrFeed jQuery call back function (which is not a valid JSON response).
I know we can remove JSON callback method for Flickr API using nojsoncallback=1
query.
But is there any better approach to handle JSONP response if it is mandatory to use JSON with Padding (JSONP)?
Instead of getting the response as a String, then trimming of the JSON padding and then parse the remaining JSON data.
Sample Flickr API response-
jsonFlickrFeed({
"title": "Recent Uploads tagged mountrainier",
"link": "http:\/\/www.flickr.com\/photos\/tags\/mountrainier\/",
"description": "",
"modified": "2016-12-15T16:56:42Z",
"generator": "http:\/\/www.flickr.com",
"items": [ {
"title": "Gateway Arts District Open Studio Tour, December 10, 2016",
"link": "http:\/\/www.flickr.com\/photos\/kimsworldofart\/31274762970\/",
"media": {
"m": "http:\/\/farm1.staticflickr.com\/381\/31274762970_c40599d623_m.jpg"
},
"date_taken": "2016-12-10T15:49:03-08:00",
"description": " <p><a href=\"http:\/\/www.flickr.com\/people\/kimsworldofart\/\">kimsworldofart<\/a> posted a photo:<\/p> <p><a href=\"http:\/\/www.flickr.com\/photos\/kimsworldofart\/31274762970\/\" title=\"Gateway Arts District Open Studio Tour, December 10, 2016\"><img src=\"http:\/\/farm1.staticflickr.com\/381\/31274762970_c40599d623_m.jpg\" width=\"240\" height=\"135\" alt=\"Gateway Arts District Open Studio Tour, December 10, 2016\" \/><\/a><\/p> <p>This photo was taken at the Otis Street Art Project in Mount Rainier, Maryland.<\/p>",
"published": "2016-12-14T20:25:11Z",
"author": "[email protected] (\"kimsworldofart\")",
"author_id": "8508061@N02",
"tags": "otisstreetartsproject gatewayartsdistrict mountrainier princegeorgescounty maryland"
}]})
How to override GSON Converter to trim of these extra function syntax and then parse the remaining valid JSON?
Using the standard
GsonConverterFactory
as guide, we can construct one that removes the JSONP from the front of the stream, thus avoid having to read the whole thing and trim --and the converter body. By creating our own json reader, we avoid the assertion that the stream was fully consumed. This allows us to leave the closing JSONP elements in the stream when we close it.
add to your retrofit like you would the regular Gson factory --
Note: using this converter will require all responses to be in JSONP. It will fail on regular JSON responses, and you cannot use the Gson and GsonP converters at the same time.