簡體   English   中英

如何 JSON 序列化實體類?

[英]How to JSON serialize an entity class?

我正在嘗試將一個復雜的對象添加到 Redis 中,但是在從 Redis 檢索值時,我將某些值設為 null。 下面是我正在嘗試的粗略樣本。 我有一個復雜對象,我使用 JsonConvert 序列化該復雜對象並將其添加到 Redis 中。 屬性 CollectionID 有兩個具有各自值的計數,但是在從 Redis 和反序列化獲取它之后,該值會變為空值。

問題是“客戶”類是一個實體對象,而 json 序列化無法序列化該特定對象 c#。 這種情況有什么可能的解決方案嗎?

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 : Entity
{
    .
    .
    .
    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; }
}

我認為問題在於您的公共屬性沒有一個只有 getter 的 setter。

請嘗試添加 setter 並再次檢查。

我希望有幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM