How to cope with differences in the GET and POST JSON scheme of WP-API

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:

Read More
{
"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!

Related posts

1 comment

  1. 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!

Comments are closed.