Adrian Adrian - 1 year ago 88
JSON Question

Can't deserialize JSon to C#

I have the following JSon returned in my windows forms app .net 4, but i can get the Avatar URLs! attempts either yield a null value or in my current attempt below an unexpected character

Here is the JSon:

{"self":"","key":"zzzzzz","name":"firstname.lastname","emailAddress":"","avatarUrls":{"16x16":"","24x24":"","32x32":"","48x48":""},"displayName":"Lastname, FirstName","active":true,"timeZone":"Europe/Dublin","locale":"en_UK","groups":{"size":1,"items":[]},"applicationRoles":{"size":1,"items":[]},"expand":"groups,applicationRoles"}

and here is my current attempt to get the URLs, the above json is passed in "result":
I'm using Newtonsoft JSON library

var response = JsonConvert.DeserializeObject<myselfResponse>(result);

public class myselfResponse
public string username { get; set; }

public string key { get; set; }

public string name { get; set; }

public string emailAddress { get; set; }

//public AvatarUrls avatarUrls { get; set; }

public string avatarUrls { get; set; }

public class AvatarUrls
public string _16x16 { get; set; }
public string __invalid_name__24x24 { get; set; }
public string __invalid_name__32x32 { get; set; }
public string __invalid_name__48x48 { get; set; }

the error i get is unexpected character

Any help would be great thanks in advance...

Answer Source

You seem to have commented out the correct property of type AvatarUrls and replaced it with a string property. Don't do that.

And as you've already discovered you can set the property names for JSON properties to anything with the JsonProperty attribute. So, uncomment that line, remove the extra string property, and do this to your "invalid name" properties:

public string Size16x16 { get; set; }

Or if you'd prefer it to be dynamic don't use a separate object at all and do this:

public Dictionary<string, string> AvatarUrls { get; set;}

Note that by using JsonProperty you can also use correct naming in C# and capitalize property names.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download