JSON.NET(WebApi2) - 序列化属性,但反序列化过程跳过 [英] JSON.NET (WebApi2) - Serialize property, but skip during deserialization
问题描述
我知道 [JsonIgnore]
这完全忽略了性,我知道 ShouldSerializePropertyName
的赋予有条件的序列化,但我找不到任何标记属性被序列化为JSON正常,但反序列化过程中未设置。
I know of [JsonIgnore]
which ignores properties altogether, I know of ShouldSerializePropertyName
which gives conditional serialization, but I cannot find anything to mark property to be serialized into JSON normally, but not set during deserialization.
我可以写一个解决方法:
I could write a workaround:
[JsonIgnore]
public string MyValue{get;set;}
public string MyValueForJson {get{return MyValue;}
但它是一个不得已而为之。是否有某种方式 - 不是自定义转换器等其他 - 我不希望这一领域的反序列化过程中被填充到EX preSS
but it is a last resort. Is there some way - other than custom converters etc. - to express that I don't want that field to be populated during deserialization?
推荐答案
据我了解,你想用JSON字符串的所有属性序列化对象,但只提取选定的性能,同时反序列化该字符串。
As I understand you want to serialize object with all properties in json string but retrieve only selected properties while deserialization on that string.
如果这是这样,那么,我就在那里我创建了基本类型和DerivedType类的话,我序列化派生类型为JSON字符串反序列化的同时,我希望它在基本类型实例类似的规定。所以写了这个code:
If this is case then, I had a similar requirement where I created BaseType and DerivedType classes then I serialize derived type into Json string while deserialization I want it in Base type instance. So wrote this code :
using System.Web.Script.Serialization;
public static TB CastToBase<T, TB>(this T derivedTypeInstance)
{
var serializer = new JavaScriptSerializer();
var baseTypeInstance = serializer.Deserialize<TB>(serializer.Serialize(derivedTypeInstance));
return baseTypeInstance;
}
这篇关于JSON.NET(WebApi2) - 序列化属性,但反序列化过程跳过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!