简体   繁体   English

将类序列化为JSON时如何修改其名称

[英]How to modify the name of a class when serializing it to JSON

I have an entity class as shown below. 我有一个实体类,如下所示。 I am using Json.Net to serialize it to JSON. 我正在使用Json.Net将其序列化为JSON。 Now there are couple of fields / properties in the class which need to be serialized with different names from the actual properties, and that is easily achievable using the [JsonProperty] attribute as shown in the code below. 现在,类中有几个字段/属性需要使用与实际属性不同的名称进行序列化,并且可以使用[JsonProperty]属性轻松实现,如下面的代码所示。 But what if I need to change the name of the main entity itself, which is marked with the [JsonObject] attribute? 但是,如果我需要更改以[JsonObject]属性标记的主体实体本身的名称,该怎么办? (Here I am talking about the UserDashboards class which is derived from EntityBase<int> .) I have tried adding a few named parameters like title, id, etc. but they did not help. (在这里,我谈论的是从EntityBase<int>派生的UserDashboards类。)我尝试添加一些命名参数,例如title,id等,但它们没有帮助。

     [JsonObject]
     public class UserDashboards : EntityBase<int>
     {  
        public int UserID { get; set; }
        public int DashboardID { get; set; }
        public int DashboardSequence { get; set; }
        public string DashboardTitle { get; set; }
        public int PermissionLevelID { get; set; }
        [JsonProperty("IsHome")]
        public Nullable<bool> IsHomeDashboard { get; set; }
        [JsonProperty("IsShared")]
        public Nullable<bool> IsSharedDashboard { get; set; }             
      }

If your object is at the root level in the JSON, it cannot be assigned a name. 如果您的对象位于JSON的根级别,则无法为其分配名称。 Objects in JSON actually do not have names, per the specification (see JSON.org ). 根据规范,JSON中的对象实际上没有名称(请参阅JSON.org )。 Object properties have names. 对象属性具有名称。 So if you effectively want to name your object in the JSON, you will need to wrap it in another object. 因此,如果您实际上想在JSON中命名对象,则需要将其包装在另一个对象中。 Then you can assign a name to that property in the wrapper object. 然后,您可以在包装对象中为该属性分配名称。 Like so: 像这样:

class Wrapper
{
    [JsonProperty("UserData")]
    public UserDashboards UserDashboards { get; set; }
}

If you then serialize the wrapper object then you will end up with JSON like this: 如果随后对包装对象进行序列化,则最终将得到JSON,如下所示:

{
    "UserData" :
    {
        "UserID" : 42,
        "DashboardID" : 26,
        "DashboardSequence" : 1,
        "DashboardTitle" : "Foo",
        "PermissionLevelID" : 99,
        "IsHome" : true,
        "IsShared" : false
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM