如何在默认值为空的字典中添加默认值

时间:2019-08-13 05:39:27

标签: c# entity-framework dictionary .net-core

我有一个enum属性

public enum UserNotificationTypes
{
    Email,
    SMS,
    Push_Messages
}

和模型类

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

我的方法是

 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);
  }

我的请求JSON看起来像

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

听说我的功能正常。我的问题是,如果键值为空,我想用false插入数据。

{

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

2 个答案:

答案 0 :(得分:1)

检查适用于您情况的JsonConverter实现,这是实现您要执行的操作的无缝方式,因为它将在反序列化过程中内部转换Json,而无需在业务逻辑中添加任何代码。这是基于属性的编程,它为该属性增加了一个附加的转换方面,在Read and Write Json中,可以合并任何数量的自定义逻辑以在序列化和反序列化期间工作

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;}
}

结果:

enter image description here

答案 1 :(得分:0)

基本上,您尝试设置false,如果您的settings.Value为空,则可以尝试以下代码

usettings.Value = string.IsNullOrEmpty(settings.Value) ? "false" : settings.Value;