Search code examples
c#json.netjavascriptserializer

Deserialize string not converting array


I have this string that I am trying to deserialize to an object, but every time it is converted the Roles Property is not converted back.

{"LoginAttemptId":235,"UserProfileId":4,"Username":"devclient1","Id":null,"SubscriptionType":null,"Roles":["Client"]}

I have tried both these Deserialization methods:

PauperToPresidentSerializedModel serializeModel = 
               JsonConvert.DeserializeObject<PauperToPresidentSerializedModel>(decUserData);

                //PauperToPresidentSerializedModel serializeModel
                //    = serializer.Deserialize<PauperToPresidentSerializedModel>(decUserData);

and both give me and object where the Roles property is Null, instead of having 'Client' in it.

here is the PauperToPresidentSerializedModel obejct definition

public class PauperToPresidentSerializedModel
    {
        public long LoginAttemptId { get; set; }

        public long UserProfileId { get; set; }
        public string Username { get; set; }

        public string Id { get; set; }

        public string SubscriptionType { get; set; }
        public string[] Roles { get; private set; }
        public PauperToPresidentSerializedModel(PauperToPresidentPrincipal principal)
        {
            LoginAttemptId = principal.LoginAttemptId;
            UserProfileId = principal.UserProfileId;
            Username = principal.Username;
            Id = principal.Id;
            SubscriptionType = principal.SubscriptionType;
            Roles = principal.Roles;
        }
        public PauperToPresidentSerializedModel()
        {            
        }
    }

Solution

  • Your Roles field has a private setter. You could:

    1. Make it public

    2. Have the contract resolver access private fields:

      contractResolver.DefaultMembersSearchFlags |= BindingFlags.NonPublic;

    3. Create a custom contract resolver (I am guessing you don't want to go that route).