1

I have a WordPress website with the WP-API plugin so I can request data for my Android app.
Until now I only fetched data, but now I want my Android users to be able to make comments on articles.
So I need to be able to create new comments through the API but I can't get it to work for me.

This is what I think is wrong:
GET request:

{
"id": ​3,
"post": ​275,
"author": ​1,
"date": "2016-05-12T12:10:03",
"content": 
{
    "rendered": "<p>asdfsdfsadf</p>\n"
}
}

Expected POST request:

{
"id": ​3,
"post": ​275,
"author": ​1,
"date": "2016-05-12T12:10:03",
"content": "<p>asdfsdfsadf</p>\n"    
}

POJO:

public class CommentModel {
    public Integer id;
    public Date date;
    public Date modified;
    public Content content;
    public int post;
    public int author;

    public class Content {
        public String rendered;
    }
}

As you can see, the POST request is formatted differently then the GET request and my POJO is modelled after the GET request.
I am using GSON for the serialization and it will create JSON which looks like the GET request; this does not work on a POST.
The request is done using retrofit and OkHTTP.

The following error is thrown in WordPress:

Warning: stripslashes() expects parameter 1 to be string, array given in wp-includes/kses.php on line 1566
{"code":"rest_cannot_read_post","message":"Sorry, you cannot read the post for this comment.","data":{"status":403}}

My question is: How to be able to post a new comment and also be able to get comments using the same POJO

I hope someone can help me!

thomas479
  • 509
  • 1
  • 6
  • 17
  • [`/sites/$site/posts/$post_ID/replies/`](https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/posts/%24post_ID/replies/), [`/sites/$site/posts/$post_ID/replies/new`](https://developer.wordpress.com/docs/api/1.1/post/sites/%24site/posts/%24post_ID/replies/new/)... This is thoroughly documented, so what's the issue? – vard May 17 '16 at 13:12
  • I am not using WordPress.com but the self hosted version (.org) with the [WP-API](http://v2.wp-api.org/) plugin. This is totally different as far as I can see. – thomas479 May 17 '16 at 13:18

1 Answers1

2

I fixed it myself, finally!

The fix was using a custom JsonSerialiser in the following way:

public static class ContentSerializer implements JsonSerializer<CommentModel.Content> {
        public JsonElement serialize(final CommentModel.Content content, final Type type, final JsonSerializationContext context) {
            return new JsonPrimitive(content.rendered);
        }
    }

and registering it with the creation of the Gson serializer:

Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
                .registerTypeAdapter(CommentModel.Content.class, new ContentSerializer())
                .create();

Then it will generate the correct JSON!

thomas479
  • 509
  • 1
  • 6
  • 17