I thought I understood how to do this, but obviously not. I have my API from Flickr, which begins like so:
jsonFlickrApi({ "photos":{ "page":1, "pages":10, "perpage":100, "total":1000, "photo":[ { "id":"12567883725", "owner":"74574845@N05", "secret":"a7431762dd", "server":"7458", "farm":8, "title":"", "ispublic":1, "isfriend":0, "isfamily":0, "url_l":"http:\/\/farm8.staticflickr.com\/7458\/12567883725_a7431762dd_b.jpg", "height_l":"683", "width_l":"1024" }
Now the information I need to get is from within the photo array, so what I have been trying to do is:
interface ArtService { @GET("/services/rest/?method=flickr.photos.getRecent&extras=url_l&owner_name&format=json") PhotosResponse getPhotos(); public class PhotosResponse { Photos photos; } public class Photos { List<Arraz> photo; } public class Arraz { int id; String title; String owner; String url_l; } }
Very clear that I seem to be missing the point, however I am unsure of how to get the information..
Retrofit is a REST Client for Java and Android allowing to retrieve and upload JSON (or other structured data) via a REST based You can configure which converters are used for the data serialization, example GSON for JSON.
You can use JSON to Kotlin Data class converter plugin in Android Studio for JSON mapping to POJO classes (kotlin data class). This plugin will annotate your Kotlin data class according to JSON. Then you can use GSON converter to convert JSON to Kotlin. If you want to parse json manually.
I would suggest using http://www.jsonschema2pojo.org. You can paste your JSON and it will generate the POJOs for you.
That should do the trick.
A quick look at Retrofit's docs says it uses Gson to convert JSON to Java classes. This means you need a class hierarchy in Java that matches the JSON. Yours ... doesn't.
The returned JSON is an object with a single field "photos" that holds an object;
{ "photos" : { ... } }
So, your top level class would be a Java class with a single field:
public class PhotosResponse { private Photos photos; // getter/setter }
And that Photos
type would be another class that matches the JSON for the object that field contains:
{ "page":1, "pages":10, ... }
So you'd have:
public class Photos { private int page; private int pages; private int perpage' private int total; private List<Photo> photo; // getters / setters }
And then you'd create a Photo
class to match the structure of the object in that inner array. Gson will then map the returned JSON appropriately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With