Adrian
Adrian

Reputation: 1149

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":"http://jira.prod.xxxxxx.com/rest/api/2/user?username=firstname.lastname","key":"zzzzzz","name":"firstname.lastname","emailAddress":"[email protected]","avatarUrls":{"16x16":"http://jira.prod.xxxxxx.com/secure/useravatar?size=xsmall&ownerId=zzzzzz&avatarId=12500","24x24":"http://jira.prod.xxxxxx.com/secure/useravatar?size=small&ownerId=zzzzzz&avatarId=12500","32x32":"http://jira.prod.xxxxxx.com/secure/useravatar?size=medium&ownerId=zzzzzz&avatarId=12500","48x48":"http://jira.prod.xxxxxx.com/secure/useravatar?ownerId=zzzzzz&avatarId=12500"},"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
{
    [JsonProperty("username")]
    public string username { get; set; }

    [JsonProperty("key")]
    public string key { get; set; }

    [JsonProperty("name")]
    public string name { get; set; }

    [JsonProperty("emailAddress")]
    public string emailAddress { get; set; }

    //public AvatarUrls avatarUrls { get; set; }

    [JsonProperty("avatarUrls")]
    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...

Upvotes: 0

Views: 151

Answers (1)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

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:

[JsonProperty("16x16")]
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:

[JsonProperty("avatarUrls")]
public Dictionary<string, string> AvatarUrls { get; set;}

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

Upvotes: 2

Related Questions