Search code examples
c#json.netgoogle-directory-api

UserLocation object conversion missing in directory API


.NET / Google directory API

I'm working with a few of the attributes in the directory API.

On phones, for example, I can do something like this:

System.Collections.Generic.IList <Google.Apis.Admin.Directory.directory_v1.Data.UserPhone> phone = results.Phones

And I'll get a list of phone numbers associated with the user. So this works along with all of the other objects thus far that I'm working with until I came across "location" which appears to be "UserLocation" in the directory API. I did verify that the object looks like matches the location json when I call getUser().

This line:

System.Collections.Generic.IList<Google.Apis.Admin.Directory.directory_v1.Data.UserLocation> loc = results.Locations;

is not valid / does not compile:

"Cannot implicitly convert type 'object' to 'System.Collections.Generic.IList'."

When I inspect the results from getUser in the API, this field doesn't have a type like the rest of the fields (eg phone), it's a generic "object {Newtonsoft.JSon.linq.JArray}"

No big deal, I tried to manually convert the JSON array using this: (implicitly typed so I'm ensuring I've got the right object) System.Collections.Generic.IList location = JsonConvert.DeserializeObject(results.Locations.ToString());

This also does not compile:

"Cannot implicitly convert type 'Google.Apis.Admin.Directory.directory_v1.Data.UserLocation' to 'System.Collections.Generic.IList'. An explicit conversion exists (are you missing a cast?)"

I didn't see multiple locations in the google admin panel so I thought it may be misreporting as an array so I tried this line:

Google.Apis.Admin.Directory.directory_v1.Data.UserLocation location = (Google.Apis.Admin.Directory.directory_v1.Data.UserLocation)results.Locations;

Which compiles ok / no errors or warnings. But when run I get:

System.InvalidCastException: 'Unable to cast object of type 'Newtonsoft.Json.Linq.JArray to type Google.Apis.Admin.Directory.directory_v1.Data.UserLocation;'

First, this looks like a bug in the Google .Net API and I'll be opening a bug ticket on it. But I need to get past this now for the short term. How can I convert this object to the UserLocation[] type?


Solution

  • Found the answer, this is the method that works to deserialize the object into an iList (strongly typed but not necessary to do so):

    IList<Google.Apis.Admin.Directory.directory_v1.Data.UserLocation> location = 
    JsonConvert.DeserializeObject<IList<Google.Apis.Admin.Directory.directory_v1.Data.UserLocation>>(results.Locations.ToString());