简体   繁体   中英

How to get class properties in order of declaration when serialize

I have a List<CampaignModel> that I need to serialize using JsonConvert.SerializeObject

Everything works fine except Im getting the properties in a diferent order than the class declaration.

My class declaration is:

 public class CampaignModel
    {
        public string Checked { get; set; }
        public int CampaignId { get; set; }
        public string Name { get; set; }
        public string Market { get; set; }
        public string Type { get; set; }
        public bool IsActive { get; set; }
        public bool Active { get; set; }
    }

And the order Im getting the properties in my json is:

在此输入图像描述

Any clue?

Properties are not guaranteed to have or maintain any specific order in JavaScript. What you will do in your C# code can't change this "limitation".

BTW, the same goes for .net .

You can use the JsonProperty attribute

[JsonProperty(Order = 1)]

Documentation: JsonPropertyAttribute order

So assuming the order you want is the order in your code, you would have something like this:

public class CampaignModel
{
    [JsonProperty(Order = 1)]
    public string Checked { get; set; }
    [JsonProperty(Order = 2)]
    public int CampaignId { get; set; }
    [JsonProperty(Order = 3)]
    public string Name { get; set; }
    [JsonProperty(Order = 4)]
    public string Market { get; set; }
    [JsonProperty(Order = 5)]
    public string Type { get; set; }
    [JsonProperty(Order = 6)]
    public bool IsActive { get; set; }
    [JsonProperty(Order = 7)]
    public bool Active { get; set; }
}

The reason for setting the order on all properties is because any without will be given the default of -1. Which will place them before any ordered properties.

A .Net Fiddle (forked from Brian Rogers) showing a quick example of the attributes use - https://dotnetfiddle.net/wr2KRh

You can specify the order for the members of a class you wish to serialize. The basic rules for data ordering include:

  • If a data contract type is a part of an inheritance hierarchy, data members of its base types are always first in the order
  • Next in order are the current type's data members that do not have the Order property of the DataMemberAttribute attribute set, in alphabetical order
  • Next are any data members that have the Order property of the DataMemberAttribute attribute set. These are ordered by the value of the Order property first and then alphabetically if there is more than one member of a certain Order value. Order values may be skipped.

So you may specify the order of the members of the class with the Order property:

[JsonProperty(Order = 1)]

More about JSON Serialization on MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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