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

How to store complex object in redis hash in c#?

我必须将复杂对象存储到 Redis 的哈希中 cash.I 我正在使用 stackexchange.redis 来执行 this.My Class 如下所示。

 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 中,但不是因为我 want.I 得到的结果如下图所示。 我想要 json format.So 中的 UserList 值,我该怎么做。

好像序列化出了问题。在 JSON 和 .NET 对象之间转换的最佳方法是使用 JsonSerializer:

JsonConvert.SerializeObject(fooObject);

您可以从 Serializing and Deserializing JSON 查看更多详细信息。

还有一个好办法,你可以试试IRedisTypedClient,它是ServiceStack.Redis的一部分。

IRedisTypedClient - A high-level 'strongly-typed' API available on Service Stack's C# Redis Client to make all Redis Value operations to apply against any c# type. Where all complex types are transparently serialized to JSON using ServiceStack JsonSerializer - The fastest JSON Serializer for .NET.

希望这对您有所帮助。

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

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