Adrian Buzea
Adrian Buzea

Reputation: 836

Deserializing json into object: wrapper class workaround

This is my json

{
    "accessType":"Grant",
    "spaces":[{"spaceId":"5c209ba0-e24d-450d-8f23-44a99e6ae415"}],
    "privilegeId":"db7cd037-6503-4dbf-8566-2cca4787119d",
    "privilegeName":"PERM_RVMC_DEV",
    "privilegeDescription":"RVMC Dev",
    "privilegeType":"Permission"
}

And here's my class:

public class ProfilePrivilege
{
    public AccessType AccessType { get; set; }
    public Guid PrivilegeId { get; set; }
    public string PrivilegeName { get; set; }
    public string PrivilegeDescription { get; set; }
    public PrivilegeType PrivilegeType { get; set; }
    public List<Guid> spaces;
}

When the spaces array is not null I get an error deserializing. I can get around this by simply creating a wrapper class for Guid

public class Space
{
    public Guid spaceId;   
}

and then instead of List<Guid> I can have a List<Space> in my Privilege class and it's all fine. But I was wondering if there's a better way to do this as I don't want to have a redundant wrapper class just for that. So is there any easy way to get around this without writing a custom deserializer for my Privilege type objects ?

I'm deserializing with JSON.Net btw.

Upvotes: 4

Views: 2316

Answers (2)

Brian Rogers
Brian Rogers

Reputation: 129797

You can use a simple JsonConverter class to flatten the spaces object array to a list of GUIDs, thereby eliminating the need for the wrapper class.

Here is the code you would need for the converter:

class SpaceListConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<Guid>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return JArray.Load(reader)
                     .Children<JObject>()
                     .Select(jo => Guid.Parse((string)jo["spaceId"]))
                     .ToList();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

To use it, annotate the Spaces property in your ProfilePrivilege class with a [JsonConverter] attribute like this:

public class ProfilePrivilege
{
    ...
    [JsonConverter(typeof(SpaceListConverter))]
    public List<Guid> Spaces;
    ...
}

Then, when you deserialize, everything should "just work".

Full demo here: https://dotnetfiddle.net/EaYgbe

Upvotes: 2

Fidel
Fidel

Reputation: 7397

You don't necessarily need to create POCOs. An alternative is to use dynamics:

dynamic d = JObject.Parse(jsonString);

Console.WriteLine(d.accessType);
Console.WriteLine(d.spaces.Count);
Console.WriteLine(d.spaces[0].spaceId);

Upvotes: 0

Related Questions