如何在C#中将复杂对象存储在Redis哈希表中?

4
我需要将复杂的对象存储到Redis缓存的哈希表中。我使用StackExchange.Redis库完成此操作。我的类如下所示。
 public class Company
   {
      public string CompanyName { get; set; }
      public List<User> UserList { get; set; }
   }
   public class User
   {

    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Twitter { get; set; }
    public string Blog { get; set; }
   }

我用的存储数据到Redis的代码片段如下:

db.HashSet("Red:10000",comapny.ToHashEntries());

//以Redis格式序列化:

public static HashEntry[] ToHashEntries(this object obj)
{
    PropertyInfo[] properties = obj.GetType().GetProperties();
    return properties
        .Where(x => x.GetValue(obj) != null) // <-- PREVENT NullReferenceException
        .Select(property => new HashEntry(property.Name, property.GetValue(obj)
        .ToString())).ToArray();
}

我可以将数据存储在Redis中,但不是我想要的方式。我得到的结果如下图所示。 result after saving data in redis desktop manager 我希望以JSON格式获取UserList值。那么,我该怎么做呢?


1
你可以尝试使用CachingFramework.Redis,它是一个SE.Redis的包装器,具有可配置的序列化机制等增强功能。 - thepirat000
2个回答

4

可能最简单的方法是检查每个属性值是否为一个集合(请参见我修改后的方法中的注释):

public static HashEntry[] ToHashEntries(this object obj)
{
    PropertyInfo[] properties = obj.GetType().GetProperties();
    return properties
        .Where(x => x.GetValue(obj) != null) // <-- PREVENT NullReferenceException
        .Select
        (
              property => 
              {
                   object propertyValue = property.GetValue(obj);
                   string hashValue;

                   // This will detect if given property value is 
                   // enumerable, which is a good reason to serialize it
                   // as JSON!
                   if(propertyValue is IEnumerable<object>)
                   {
                         // So you use JSON.NET to serialize the property
                         // value as JSON
                         hashValue = JsonConvert.SerializeObject(propertyValue);
                   }
                   else
                   {
                        hashValue = propertyValue.ToString();
                   }

                   return new HashEntry(property.Name, hashValue);
              }
        )
        .ToArray();
}

3

似乎序列化有些问题。在JSON和.NET对象之间进行转换的最佳方式是使用JsonSerializer

JsonConvert.SerializeObject(fooObject);

您可以从序列化和反序列化 JSON中了解更多详细信息。
此外,还有另一种好方法,您可以尝试使用IRedisTypedClient,它是ServiceStack.Redis的一部分。

IRedisTypedClient - 高级“强类型”API可用于Service Stack C# Redis客户端,使所有Redis值操作适用于任何C#类型。在这里,所有复杂类型都会使用ServiceStack JsonSerializer自动转换为JSON——.NET最快的JSON序列化器。

希望这可以帮助您。

3
但是这个问题不是关于SE.Redis吗? - Matías Fidemraizer
@MatíasFidemraizer 对不起,我已经更新了我的答案,似乎序列化有些问题,使用Json.NET是一个好方法。 - McGrady

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接