我有一个包含一些受保护的私有成员的测试类:
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
}
该文档仅包含公共成员。 如何保存非公开成员?
谢谢!
答案 0 :(得分:4)
JSON.NET无法访问非公共属性,这就是为什么它无法处理它们。根本看不到它们。
您可以做的是编写自己的ContractResolver
,它使用反射来获取非公共属性。
然后,您可以在JsonSerializerSettings
或操作级别上简单地提供DocumentClient
。
此处描述了这样做的方法:JSON.Net: Force serialization of all private fields and all fields in sub-classes