Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I control the order of properties in my JSON output?

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();
}
like image 275
DenaliHardtail Avatar asked Feb 15 '12 02:02

DenaliHardtail


People also ask

How do I order JSON properties?

The @JsonPropertyOrder is an annotation to be used at the class-level. It takes as property a list of fields that defines the order in which fields can appear in the string resulting from the object JSON serialization.

Does JSON maintain order?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine): An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

Does order of fields matter in JSON?

The JSON RFC (RFC 4627) says that order of object members does not matter.

What is JsonProperty C#?

This sample uses JsonPropertyAttribute to change the names of properties when they are serialized to JSON. Types. public class Videogame { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("release_date")] public DateTime ReleaseDate { get; set; } }


2 Answers

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.

like image 161
M.Babcock Avatar answered Oct 16 '22 16:10

M.Babcock


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.

like image 37
findcaiyzh Avatar answered Oct 16 '22 15:10

findcaiyzh