wp-net / WordPressPCL

This is a portable library for consuimg the WordPress REST-API in (almost) any C# application
MIT License
338 stars 129 forks source link

Custom Request with User model #195

Closed BrettButcher closed 4 years ago

BrettButcher commented 4 years ago

Hi, I am not sure if I am just needing help here or have found an issue. I am trying to get more details about the user. The client.Users.GetCurrentUser method uses /me?embed and returns the basic info. I want to get the users Roles in the WP site and you can do this with /me?context=edit (for example).

I have the following code lines, the first works fine but I get an error with the second: var user = await client.Users.GetCurrentUser(); var fulluser = await client.CustomRequest.Get<IEnumerable<User>>("wp/v2/users/me?context=edit",false,true);

The call is executed fine but the result is failing at the json parser I think with whis error message:

JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable`1[WordPressPCL.Models.User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'id', line 1, position 6.

I have monitored both reponses with Fiddler and done a JSON Compare - The one on the left is the one returned from the 'context=edit' call. image

The wiki said that the CustomRequest needs its own model. But I would have thought that the User model seems fine. As far as I can see, the JSON looks fine in both ? Am I missing something or is there an issue.

ThomasPe commented 4 years ago

Since you're querying for "me" I'd expect just a single object to be returned, not a list of users (which seems to be the case looking at your JSON response). So you can try serializing directly into a User object, not a IEnumerable:

var fulluser = await client.CustomRequest.Get<User>("wp/v2/users/me?context=edit",false,true);

BrettButcher commented 4 years ago

Thasnk you @ThomasPe. Just got to your comment as I was doing just that ... I was thrown by the example in the Wiki where it uses an IEnumerable for ContactFormItem(s).. Cheers.