C# 如何将一个对象序列化/反序列化到/从 Dictionary<string,Object> 以将其保存/加载到 Couchbase.lite

标签 c# serialization deserialization couchbase couchbase-lite

如果我想在 Clouchbase.lite 中将数据存储为文档,则必须采用这样的字典形式:

var properties = new Dictionary<string, object>()
    {
        {"type", "list"},
        {"title", "title"},
        {"created_at", DateTime.UtcNow.ToString ("o")},
        {"owner", "profile:" + userId},
        {"members", new List<string>()}
    };
var rev = document.PutProperties(properties);

如何从任何 C# 对象自动创建这样的字典? 如果我理解 couchbase.lite 文档,这个过程不会递归,只是在我的对象字段和属性的第一级。

我如何从这样的字典中重新创建我的对象?

最佳答案

好的,这不是我问题的完整答案,但它暂时解决了问题。我想到了将整个对象放入交给 Couchbase.Lite 的字典中的解决方案:

    var c = new TestClass() {TestString = "SimpleStringfield", TestDate = DateTime.Today,TestStringProperty = "TestStringPropertyContent",
                              TestStringList = new List<string>(new string[] { "item1","item2","item3"})};


    var manager = Manager.SharedInstance;
    var db = manager.GetDatabase("test_database");
    if (db == null)
    {
        System.Diagnostics.Debug.WriteLine("--------------------------Could not open Database");
    }

    var doc = db.CreateDocument();
    var properties = new Dictionary<string,Object>() { {"type","day"}, {"day",c} };

    var rev = doc.PutProperties(properties);

    var docread = db.GetDocument(doc.Id);
    JObject testobject = (JObject)docread.GetProperty("day");

    var o = testobject.ToObject<TestClass>();
}

最后 o 包含与 c 相同的值。

我想指出 Jim Borden 给我的警告:

I will always assert that the "right way" is the way that works. The fact that the library uses JSON .NET internally is an implementation detail, though. If that were to change for some reason then this way would break. I also have a feeling that if the class were more complex than your example than it would break as well. We are currently designing a cross platform specification to do just what you want to do (save classes directly to the database without converting to a dictionary first). This will be a slow process though because there is a lot of thought that needs to go into it (not just for C#, but for Java and Objective-C as well). For example, how to serialize a class that has a property which references back to it, etc. I know JSON .NET already does this, but I don't want to start exposing JSON .NET into the public API because eventually it should be switchable (in case JSON .NET does not work for whatever reason on a platform).

关于C# 如何将一个对象序列化/反序列化到/从 Dictionary<string,Object> 以将其保存/加载到 Couchbase.lite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36178057/

相关文章:

java - 如何使用 jackson 遍历生成的 json 模式并将自定义属性放入 json 模式

c# - WPF TextBox 滚动到结束只工作一次

c# - 我可以避免 Entity Framework 使用 SQL_VARIANT 来查询吗?

java - 序列化对象时包含外部变量

java - 如何使用 UDP 将结构从 C 应用程序发送到 Java 应用程序

c# - 小文件导致 OutofMemoryException

java - 当 JsonProperty 有时是数组有时是单个对象时,Jackson 反序列化

c# - "managed"代码到底是什么?

C# + OracleSQL - 不能在 CommandText 中使用参数

serialization - 如何使用 Json.NET 在 C# 中序列化 "union-like"字段