Mr.Mojo Mr.Mojo - 3 months ago 32
JSON Question

Deserialize nested JSON tags and attachments from Wordpress API JSON response

I am using Retrofit 2 in an Android app to communicate with WordPress API but I have problems to get the attachments and tags from posts.

The corresponding JSON response looks like this:

{

"ID": 1,
"site_ID": 1,
"author": {
},
"tags": {
"Doom": {
"ID": 654,
"name": "Doom",
"slug": "doom",
"description": "",
"post_count": 53
},
"Ego-Shooter": {
"ID": 73,
"name": "Ego-Shooter",
"slug": "ego-shooter",
"description": "",
"post_count": 724
},
"id Software": {
"ID": 127,
"name": "id Software",
"slug": "id-software",
"description": "",
"post_count": 41
}
}
"attachments": {
"54344": {
"ID": 54344,
"URL": "",
"guid": "",
"mime_type": "image/jpeg",
"width": 843,
"height": 499
},
"54345": {
"ID": 54345,
"URL": "",
"guid": "",
"mime_type": "image/jpeg",
"width": 800,
"height": 1600
}
}


}

Post.class:

public class Post {

@SerializedName("ID")
private int ID;

@SerializedName("title")
private String title;

@SerializedName("content")
private String content;

@SerializedName("featured_image")
private String featuredImage;

@SerializedName("date")
private String date;

@SerializedName("URL")
private String URL;

@SerializedName("author")
private Author author;

@SerializedName("discussion")
private Discussion discussion;

@SerializedName("attachments")
private Attachment attachments; // At this point I have problems
}


Attachment.class

public class Attachment {

@SerializedName("URL")
private String URL;

@SerializedName("width")
private int width;

@SerializedName("height")
private int height;


}

Everything works fine except the nested JSON objects in attachments or tags. The Attachment object does only contain default values and is not filled with the correct values from the JSON response.

My Retrofit builder:

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(WordPressService.ENDPOINT)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit.create(WordPressService.class);


I would like to have a list of attachment objects but I do not know how I can solve this problem.

Answer

To parse the attachments and tags JSON elements use a LinkedTreeMap.

Update the Post class as follows:

public class Post {

  @SerializedName("ID")
  private int ID;

  @SerializedName("title")
  private String title;

  @SerializedName("content")
  private String content;

  @SerializedName("featured_image")
  private String featuredImage;

  @SerializedName("date")
  private String date;

  @SerializedName("URL")
  private String URL;

  @SerializedName("tags")
  LinkedTreeMap<String, Tag> tags;

  @SerializedName("attachments")
  LinkedTreeMap<String, Attachment> attachments;
}