使用JSON设置私有属性 [英] Using JSON to set private properties
本文介绍了使用JSON设置私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用从Web服务获取的JSON值设置某些私有属性的值.
A)这可能吗
B)如果是,该怎么办?
让我再次重申.我需要公共财产才能拥有私人二传手.我尝试将设置器设置为内部,然后更改AssemblyInfo文件以将内部公开给Newtonsoft.Json.这也不行吗?
这是我的代码:
I am trying to set the values of some private properties with JSON values that I am getting from a web service.
A) Is this possible
B) If so, how do I do it?
Let me re-iterate. I need the public property to have a private setter. I have tried setting the setter to internal and then changing the AssemblyInfo file to expose internals to Newtonsoft.Json. This doesnt work either?
Here is my code:
using (WebClient wc = new WebClient())
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(MyAmazingObject));
return (FacebookUser)js.ReadObject(wc.OpenRead("URL_HERE"));
}
推荐答案
很遗憾,Vivek的回答不正确.
如果使用数据合约,则可以使用私有成员的序列化.您需要使用System.Runtime.Serialization.Json.DataContractJsonSerializer,请参阅 http ://msdn.microsoft.com/zh-CN/library/system.runtime.serialization.json.datacontractjsonserializer.aspx [ http://msdn.microsoft.com/en-us/library/ms733127.aspx [^ ].
使用数据协定时,元数据不仅由访问说明符定义,而且由特殊属性(例如[DataMember])定义.与常规的旧版"序列化相比,数据契约更具非侵入性,并且更具优势.
另请参阅我过去提倡数据合约方法的答案:
如何在我的表单应用程序? [ ^ ],
创建属性文件... [
The answer by Vivek is unfortunately incorrect.
You can use serialization of private members if you use Data Contract. You need to use System.Runtime.Serialization.Json.DataContractJsonSerializer, see http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx[^].
To get the idea, read this: http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].
When you use Data Contract, the meta-data is defined not just by access specifier, but by special attributes such as [DataMember]. Data Contract is much more non-intrusive and beneficial over regular "legacy" serialization.
Please see also my past answer where I advocate Data Contract approach:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating a property files...[^].
—SA
这篇关于使用JSON设置私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文