2017-02-11 26 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