我有一个包含一些 protected 和私有(private)成员的测试类:
public class Doc_PrivateValues : Document
{
public int PublicIntProperty { get; set; }
public int PublicIntField;
protected int ProtectedIntProperty { get; set; }
protected int ProtectedIntField;
private int PrivateIntProperty { get; set; }
private int PrivateIntField;
public SimpleDocument PublicDocument;
protected SimpleDocument ProtectedDocument;
private SimpleDocument PrivateDocument;
public SimpleStruct PublicStruct;
protected SimpleStruct ProtectedStruct;
private SimpleStruct PrivateStruct;
}
我以非常简单的方式将此文档保存到 CosmosDB 中:
Microsoft.Azure.Documents.Document result = CosmosClient.CreateDocumentAsync( CosmosCollection.SelfLink, document ).Result.Resource;
document.id = result.Id;
数据库中的结果:
{
"PublicIntField": 2,
"PublicDocument": {
"StrVal": "seven",
"IntVal": 7,
"id": null
},
"PublicStruct": {
"StrVal": "ten",
"IntVal": 10
},
"PublicIntProperty": 1,
"id": "58f18ccf-9e0c-41a6-85cd-a601f12a120a",
"_rid": "mPlfANiOud4BAAAAAAAAAA==",
"_self": "dbs/mPlfAA==/colls/mPlfANiOud4=/docs/mPlfANiOud4BAAAAAAAAAA==/",
"_etag": "\"00000000-0000-0000-8b2a-d853688c01d4\"",
"_attachments": "attachments/",
"_ts": 1543856923
}
文档仅包含公共(public)成员。 我怎样才能同时保存非公共(public)成员?
谢谢!
最佳答案
JSON.NET 无法访问非公共(public)属性,这就是它无法处理它们的原因。它根本看不到它们。
您可以编写自己的 ContractResolver
,它使用反射来获取非公共(public)属性。
然后您可以简单地在 DocumentClient
或操作级别上提供 JsonSerializerSettings
。
这里描述了这样做的方法:JSON.Net: Force serialization of all private fields and all fields in sub-classes
关于c# - 为什么 CosmosDB 只保存公共(public)成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53598632/