wcfdictionarydatacontractjsonserializerjson-serialization

WCF REST service dictionary serialization


I'm having trouble with serializing dictionary in my WCF service.

[DataContract]
    public class UserInfo
    {
        [DataMember]
        public Guid ID { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public IDictionary<string, List<string>> Permissions { get; set; } = new Dictionary<string, List<string>>();
    }

This is example of current response

{
    "ID": "1",
    "Name": "admin",
    "Permissions": [
        {
            "Key": "Users",
            "Value": [
                "Read",
                "Edit"
            ]
        },
        {
            "Key": "Management",
            "Value": [
                "Read"
            ]
        }
    ]
}

and this is desired response

{
    "ID": "1",
    "Name": "admin",
    "Permissions": {
        "Users": ["Read", "Edit"],
        "Management": ["Read"]
    }
}

Is there way to implement this globally or on specific property?


Solution

  • I've solved it by using custom made dictionary as explained here.

    Since I've created this type for serialization

    AjaxDictionary<string, string[]>
    

    I had to add

    [ServiceKnownType(typeof(string[]))]
    

    on my class that is ServiceContract for returning responses.