温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Values are being null while getting it from Redis for complex objects

c# - 从Redis获取复杂对象的值是空的

发布于 2020-03-30 21:43:42

我想将一个复杂的对象添加到Redis中,但是在从Redis中检索值时,我将某些值设为null。以下是我尝试的粗略示例。我有一个复杂的对象,我使用JsonConvert序列化了这个复杂的对象,并将其添加到Redis中。属性CollectionID具有两个带有各自值的计数,但是从Redis获取并进行反序列化后,该值将为null。请检查下图

属性CollectionID具有两个带有ID的值:

在此处输入图片说明

从Redis缓存获取属性时,该属性变为null 所以

下面是示例:

class Program
{
    private static IDatabase _cache;
    private static ConnectionMultiplexer _connection;

    static void Main(string[] args)
    {
        _connection = ConnectionMultiplexer.Connect("localhost");
        _cache = _connection.GetDatabase();

        List<Id> id = new List<Id>() { new Id() { ID = 10 }, new Id() { ID = 20 } };
        Collection<Customers> collection = new Collection<Customers>() { new Customers(id) };
        Product product = new Product(new Guid(), collection, 1);
        _cache.StringSet("Redis_Key", GetSerializedString(product));
        var value = JsonConvert.DeserializeObject<Product>(_cache.StringGet("Redis_Key"));
    }

    private static String GetSerializedString<Test1>(Test1 value)
    {
        return JsonConvert.SerializeObject(
                    value,
                    Formatting.Indented,
                    new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                        PreserveReferencesHandling = PreserveReferencesHandling.All
                    });
    }
}

public class Product
{
    public Product(
        Guid parentGuid,
        Collection<Customers> collection,
        int number)
    {
        _parentGuid = parentGuid;
        _collection = collection;
        _number = number;
    }

    private Guid _parentGuid;
    public Guid ParentGuid
    {
        get { return _parentGuid; }
    }

    private Collection<Customers> _collection;
    public Collection<Customers> Collection
    {
        get { return _collection; }
    }

    private int _number;
    public int number
    {
        get { return _number; }
    }
}

public class Customers
{
    public Customers(IEnumerable<Id> id)
    {
        _id = id;
    }

    private IEnumerable<Id> _id;

    public IEnumerable<Id> CollectionID
    {
        get { return _id; }
    }
}

public class Id
{
    public int ID { get; set; }
}

任何建议都会有很大帮助。

谢谢阿尼什

查看更多

提问者
Anish
被浏览
24
LeoMurillo 2020-01-31 19:01

问题是您没有设置器CollectionID

public IEnumerable<Id> CollectionID
{
    get { return _id; }
    set { _id = value; } //need a setter
}

如果您需要二传手private,则可以这样做,但您需要一个ContractResolver您可以添加包JsonNet.PrivateSettersContractResolvers,然后添加

using JsonNet.PrivateSettersContractResolvers;
...
var value = JsonConvert.DeserializeObject<Product>(_cache.StringGet("Redis_Key"),
        new JsonSerializerSettings
        {
            ContractResolver = new PrivateSetterContractResolver()
        });

请参阅Json.Net中的专用设置器

发布
问题

分享
好友

手机
浏览

扫码手机浏览