为什么我的JSON结果集中的公共属性下划线加前缀 [英] Why is prefix of underscore on public properties in my JSON result set

查看:330
本文介绍了为什么我的JSON结果集中的公共属性下划线加前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET WCF通过jquery调用以JSON格式返回.NET对象. 当我将.NET类更改为可序列化(通过WCF类中的方法公开)时,对象的属性名称突然更改为:

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.

所以我访问json对象的javascript类中的所有代码都是错误的.

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

为什么这些属性现在都有下划线前缀? 以及如何在不删除类的serializable属性的情况下将其改回来?

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

谢谢. 基督徒

推荐答案

当您说将类更改为可序列化"时,是否表示您在它们上添加了[Serializable]属性?在这种情况下:带有该属性的类的所有字段都已序列化(没有属性).在下面的示例中,此类没有任何属性,并且具有无参数构造函数,因此将其视为"POCO"(普通的CLR对象)类型. POCO类型将其公共成员(字段或属性)序列化.如果用[Serializable]装饰它,它将属于可序列化规则.

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.

为什么需要用[可序列化]标记您的类型?如果确实需要这样做(对于某些旧式序列化程序),则还可以用[DataContract][DataMember]属性修饰类型,这是WCF序列化程序所认可的.您将在类型上添加[DataContract],并在要序列化的 properties 上添加[DataMember].

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

这篇关于为什么我的JSON结果集中的公共属性下划线加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆