2017-02-11 332 views
0

我必须存储复杂的对象到redis cash.H我使用stackexchange.redis来做到这一点。我的类如下所示。如何将复杂的对象存储在c#中的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 我想要UserList json格式的值。所以,我该如何做到这一点。

+0

你可以试试[CachingFramework.Redis(https://开头的github .com/thepirat000/CachingFramework.Redis),SE.Redis的一个包装,增强了一些可配置的序列化机制。 – thepirat000

回答

2

也许最简单的路径检查是否每个属性值是一个集合(见注释在我的方法的修改版本):

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

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

JsonConvert.SerializeObject(fooObject); 

你可以看到从Serializing and Deserializing JSON更多细节。

另外还有一个好方法,你可以尝试使用IRedisTypedClient这是ServiceStack.Redis的一部分。

IRedisTypedClient - 一个高层次的“强类型” API的服务栈的C#Redis的客户,使所有的Redis值的操作 申请对任何C#类型提供 。使用ServiceStack JsonSerializer透明地序列化为JSON的所有复杂类型为 - 用于.NET的最快的JSON序列化程序 - 。

希望这会有所帮助。

+0

但这不是关于SE.Redis的这个问题吗? –

+0

@MatíasFidemraizer对不起,我已经更新了我的答案,看起来序列化有问题,这是使用Json.NET的好方法。 – McGrady