How do I control the order of properties in my JSO

2020-03-21 10:50发布

问题:

I have a class, named DataItem, with three properties: Id, DataValue, and CreatedDateTime. The properties are defined in the class in that order from top to bottom. This is also the order I'd like to see the properties in my JSON export. The problem is the properties in the DataItem object and in the JSON export are sorted in alphabetical order. Although there is nothing technically wrong with this format, it is a matter of readability.How do I control the order of properties in the JSON export?

I checked the dataItem wen instantiated and the properties are listed in alphabetical order. This is okay, I understand the potential usability issues of not sorting properties alphabetical.

public static List<DataItem>GetAllDataItems()
        {
            List<DataItem> dataItems = new List<DataItem>();

            SqlConnection conn = NetduinoDb.GetConnection();

            SqlCommand cmd = conn.CreateCommand();

            cmd.CommandText = "Select Id, DataValue, CreatedDateTime from XXX";
            cmd.CommandType = CommandType.Text;

            conn.Open();

            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                DataItem dataItem = new DataItem
                {
                    Id = reader["Id"].ToString(),
                    DataValue = reader["DataValue"].ToString(),
                    CreatedDateTime = reader["CreatedDateTime"].ToString()
                };

                dataItems.Add(dataItem);
            }

            reader.Close();
            conn.Close();


            return dataItems.ToList();
        }

This method is in my service implementation and returns the list of DataItems. I'm thinking I need to do something here but not sure what or how.

public List<DataItem> GetCollection()
{
    return DataRetriever.GetAllDataItems();
}

回答1:

The DataContractJsonSerializer takes into consideration the DataMember attribute which has an Order property. You can use it to tell the serializer the order of the members you want serialized.

[DataContract]
class DataItem
{
    [DataMember(Order = 1)]
    public string Id { get; set; }

    [DataMember(Order = 2)]
    public string DataValue { get; set; }

    [DataMember(Order = 3)]
    public string CreatedDateTime { get; set; }
}

Adjust the order as needed, but this is generally how it is done in WCF.



回答2:

I don't think both DataContractJsonSerializer and JSON.NET supports field order.

You can construct JSON string by yourself if Object is as simple as just having 3 fields.