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:
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.