问题描述
此刻,我正在使用REST Api,但我无法控制它,并已建立与我从Api接收到的json相对应的模型.
I'm working with a REST Api at the moment which I have no control over and have built models to correspond with the json which I receive from the Api.
有问题的Api不允许我在发布文章时将整个模型推回去,因此我需要找到一种方法来对Deserialize进行完全反序列化,但只能在序列化时写入选定的数据.
The Api in question though doesn't allow me to push the whole model back when doing a post so I need to find a way to Deserialize the json in full but only write selected data when Serializing.
到目前为止,我已经尝试了JsonIgnore,它执行了上面所说的操作,并且完全忽略了该属性.
So far I have tried JsonIgnore which does what it says on the tin and completely ignores the property.
然后我创建了一个自定义属性JsonWriteAttribute并将其应用于我要序列化的属性.
I then created a Custom Attribute JsonWriteAttribute and applied it to the properties I want to serialise.
我已经研究了重写DefaultContractResolver CreateProperties方法,然后仅获取具有该属性的属性,但是我似乎无法从该方法或Resolver中的属性中确定我是否正在执行读取或写入操作.
I've looked at overriding the DefaultContractResolver CreateProperties method to then only get properties with the attribute but I cant seem to determine from the method or a property in the Resolver if I'm doing a read or write.
我也尝试过查看自定义的JsonConverter,但是从此看来,我无法中断管道,然后必须自己处理所有写入.我在这里错过了某些东西,因为它似乎是正确的主意?
I've also tried looking at a custom JsonConverter but it seems like from that I cant interrupt a pipeline and have to then handle all the write myself. Am I missing something here as it seems like the right idea?
有人使用Json.Net进行序列化,反序列化时,找到了一种将属性标记为ReadOnly的方法吗?
Anyone figured out a way to mark a property as ReadOnly when doing serialisation, deserialization using Json.Net?
谢谢
推荐答案
有条件地序列化属性的一种可能性是ShouldSerialize
One possibility to conditional serialise a property is the ShouldSerialize
http://www.newtonsoft.com/json/help/html /ConditionalProperties.htm
您创建一个返回布尔值的方法,以确定您的属性是否应该序列化.该方法以ShouldSerialize开头,并以您的属性名称结尾.例如ShouldSerializeMyProperty
You create a method which returns a bool to determine if your property should be serialized or not. The Method starts with ShouldSerialize and ends with your property name. e.g. ShouldSerializeMyProperty
一个例子
public MyClass
{
public string MyProp { get; set; }
public string ExcludeThisProp { get; set; }
public int MyNumber { get; set; }
public int ExcludeIfMeetsCondition { get; set; }
//Define should serialize options
public bool ShouldSerializeExcludeMyProp() { return (false); } //Will always exclude
public bool ShouldSerializeExcludeIfMeetsCondition()
{
if (ExcludeIfMeetsCondition > 10)
return true;
else if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
return true;
else
return false;
}
}
这篇关于JsonConvert .NET序列化/反序列化只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!