Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - JavaScriptSerializer - custom property name

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; }

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Answering in several parts:

  1. To make a property named base, you need to prefix the name with an @:

    public int @base { get; set; }
    
  2. 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.

    If you were to switch to Json.NET, you would be able to use this attribute.

    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.

  3. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...