0

I have an enum property

public enum UserNotificationTypes
{
    Email,
    SMS,
    Push_Messages
}

and a model class

public class SaveUserSettingRequest
{
    public string UserName { get; set; }
    public Dictionary<string, string> UserNotifications { get; set; } 
}

and my method is

 List<UserSetting> userSettings = new List<UserSetting>();

 foreach (KeyValuePair<string, string> settings in request.UserNotifications)
 {
      UserSetting usettings = new UserSetting();
      usettings.Name = $"{Constants.USER_NOTIFICATION}.{((UserNotificationTypes)Enum.Parse(typeof(UserNotificationTypes), settings.Key)).ToString()}";
      usettings.Value = request.UserNotifications[settings.Key];
      usettings.UserId = userDetails.UserId;
      userSettings.Add(usettings);
  }

My request JSON looks like

{   
  "UserName": "xyz",
  "UserNotifications": {
    "Email": "true",
    "SMS": "true",
    "Push_Messages": "true"
  }
}

hear my functionality working fine.my problem is i want insert data with false in case key value is empty .

{

  "UserName": "xyz",
  "UserNotifications": {
    "Email": "",
    "SMS": "",
    "Push_Messages": ""
  }
}
Sebastian
  • 6,293
  • 6
  • 34
  • 47
Cherry R
  • 89
  • 1
  • 1
  • 7
  • prasad above lines working fine but getting an error at "true". request..like string does not contain definition request.. – Cherry R Aug 13 '19 at 06:21
  • now working as per my requirement ..thank you prasad garu .. – Cherry R Aug 13 '19 at 06:28
  • since you are consuming Json data, you shall be able to apply a custom converter to convert the empty values as false when de-serialized. That way you don't mix non business logic with the main code – Mrinal Kamboj Aug 13 '19 at 07:02

2 Answers2

1

Check out the JsonConverter implementation for your case, it is seamless way to achieve what you are trying to do since it will internally transform the Json during de-serialization without any extra piece of code in the business Logic. This is attribute based programming, which adds an additional conversion aspect to the property, in Read and Write Json any amount of custom logic can incorporated to work during serialization and de-serialization

void Main()
{
    string json = "{\"UserName\":\"xyz\",\"UserNotifications\":{\"Email\":\"\",\"SMS\":\"\",\"Push_Messages\":\"\"}}";

    var result  = JsonConvert.DeserializeObject<UserSetting>(json);

    result.Dump();
}

// Create a Custom JsonConverter
public class UserNotificationsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(UserNotifications).IsAssignableFrom(objectType);
    }

    // Custom logic in the ReadJson
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
            var userNotificationObj = serializer.Deserialize<UserNotifications>(reader);

            userNotificationObj.Email = string.IsNullOrEmpty(userNotificationObj.Email) ? "false" : userNotificationObj.Email;
            userNotificationObj.SMS = string.IsNullOrEmpty(userNotificationObj.SMS) ? "false" : userNotificationObj.SMS;
            userNotificationObj.Push_Messages = string.IsNullOrEmpty(userNotificationObj.Push_Messages) ? "false" : userNotificationObj.Push_Messages;

            return userNotificationObj;
    }

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

// UserSetting entity
public class UserSetting
{
    public string UserName {get; set;}

    // Decorate with the Custom Json Converter
    [JsonConverterAttribute(typeof(UserNotificationsConverter))]
    public UserNotifications UserNotifications {get; set;}
}

public class UserNotifications
{
    public string Email {get; set;}

    public string SMS {get; set;}

    public string Push_Messages {get; set;}
}

Result:

enter image description here

Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
  • Welcome @CherryR, this is correct way to achieve it using programming, so in your actual code implement a converter and mange the conversion internally – Mrinal Kamboj Aug 13 '19 at 07:32
  • This is right approach to fix issue at root - level, @CherryR This will help us to handle such situations in further development. +1 to you. – Prasad Telkikar Aug 13 '19 at 07:50
  • Thanks @PrasadTelkikar, check out the link - https://stackoverflow.com/questions/41088492/json-net-contractresolver-vs-jsonconverter for more information and difference between JsonConverter and the ContractResolver, which can be used at the class level – Mrinal Kamboj Aug 13 '19 at 08:23
0

Basically you are trying to set false, if your settings.Value is empty, you can try below code

usettings.Value = string.IsNullOrEmpty(settings.Value) ? "false" : settings.Value;
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44