我需要将复杂的对象存储到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中,但不是我想要的方式。我得到的结果如下图所示。
我希望以JSON格式获取UserList
值。那么,我该怎么做呢?