JavaScriptSerializer-自定义属性名称 [英] JavaScriptSerializer - custom property name
问题描述
我正在使用JavaScriptSerializer反序列化json数据. 一切工作都很好,但是我的问题是,json数据中的一个属性被命名为"base",所以我无法在C#代码中创建这样的属性. 我发现我可以手动将值映射到构造函数中的属性,但是问题是,我的DTO拥有200个属性,因此我不想手动进行此操作,而是希望找到任何其他解决方案. 我也尝试使用批注,但这是
I am using JavaScriptSerializer to deserialize json data. Everything works pretty well, but my problem is, that one property in json data is named 'base', so I cannot create such property in my C# code. I found that i can manually map values to properties in constructor, but the issue is, that my DTOs have like 200 properties, so I do not want to make this manually and would prefer to find any other solution. I also Tried to use annotations, but this:
[JsonProperty("base")]
public int baseValue { get; set; }
没有帮助我,每次将baseValue值设置为0(如果您认为此批注应该起作用,那么我可以发布我的整个代码,而不仅仅是这2行)
did not help me, value baseValue was set to 0 each time (if you think, that this annotation should work, I can post my whole code, not only this 2 lines)
有什么办法可以简单地解决我的问题?
Is there any way how could I simply solve my issue?
推荐答案
分几部分进行解答:
To make a property named
base
, you need to prefix the name with an@
:
public int @base { get; set; }
您写道,您正在使用 [JsonProperty]
用于完全不同的序列化程序, Json.NET .此属性对JavaScriptSerializer
没有影响.
You wrote that you are using JavaScriptSerializer
. The attribute [JsonProperty]
is for a completely different serializer, Json.NET. This attribute has no effect on JavaScriptSerializer
.
如果要切换到Json.NET,则可以使用此属性.
If you were to switch to Json.NET, you would be able to use this attribute.
或者,如果您要改为使用 DataContractJsonSerializer
,以使用重命名的属性来序列化您的类型.
Or, if you were to instead apply data contract attributes to your type, you could use either Json.NET or DataContractJsonSerializer
to serialize your type with renamed properties.
实际上, JavaScriptSerializer
除了编写自定义
In fact, JavaScriptSerializer
has no way to rename a property for serialization outside of writing a custom JavaScriptConverter
. This serializer is quite bare-bones; the only serialization attribute it supports is ScriptIgnore
to suppress serialization of a property.
这篇关于JavaScriptSerializer-自定义属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!