JavaScriptSerializer - custom property name

前端 未结 2 1656
故里飘歌
故里飘歌 2020-12-03 22:28

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 cre

2条回答
  •  生来不讨喜
    2020-12-03 23:01

    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.

提交回复
热议问题