Why is prefix of underscore on public properties in my JSON result set

混江龙づ霸主 提交于 2019-12-12 01:53:00

问题


I use ASP.NET WCF to return .NET objects in JSON format through jquery calls. When I changed my .NET classes to serializable, which I expose through methods in my WCF class, the objects property names suddenly changed from:

Name to _Name.

So all code in my javascript classes where I access json objects is wrong.

Why do the properties have a underscore prefix now? And how do I change it back without removing the serializable attribute on the classes?

Thanks. Christian


回答1:


When you say that you "changed the class to serializable", does it mean you added the [Serializable] attribute on them? If this is the case: classes marked with that attribute have all of their fields serialized (no properties). In the example below, this class doesn't have any attributes, and it does have a parameter-less constructor, so it's considered a "POCO" (plain-old CLR object) type. POCO types have their public members (fields or properties) serialized. If you decorate it with [Serializable], then it will fall into the serializable rule.

Why do you need to mark your type with [Serializable]? If you really need to do that (for some legacy serializer), you can also decorate your type with [DataContract] and [DataMember] attributes, which are honored by the WCF serializer. You'd add [DataContract] on the type, and [DataMember] on the properties which you want serialized.

public class Person
{
    private string _Name;
    private int _Age;

    public string Name {
        get { return this._Name; }
        set { this._Name = value; }
    }

    public string Age {
        get { return this._Age; }
        set { this._Age = value; }
    }
}


来源:https://stackoverflow.com/questions/7418942/why-is-prefix-of-underscore-on-public-properties-in-my-json-result-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!