tags:

views:

41

answers:

2

Short and sweet:

Is there a way to specify the order of fields in a serialized JSON object using JSON.NET?

It would be sufficient to specify that a single field always appear first.

A: 

There's no order of fields in the JSON format so defining an order doesn't make sense.

{ id: 1, name: 'John' } is equivalent to { name: 'John', id: 1 } (both represent a strictly equivalent object instance)

Darin Dimitrov
This only matters for the "on-the-wire" transmission, not for its consumption on the other side. Once deserialized I don't expect the order to persist, basically.
Kevin Montrose
What order are you talking about? JSON is a format allowing the serialization/deserialization of objects. There's no notion *order* in object fields in OOP.
Darin Dimitrov
@Darin - but there is an order in the serialization. "{ id: 1, name: 'John' }" and "{ name: 'John', id: 1 }" are different as *strings*, which is what I care about here. Of course, the objects are equivalent when deserialized.
Kevin Montrose
But why do you care about the string representation? Aren't you manipulating object instances?
Darin Dimitrov
@Darin - no, not in this case. I'm serializing something and then passing it along as a string to a service that only deals in strings (not JSON aware), and it'd be convenient for a variety of reasons for one field to appear first in the string.
Kevin Montrose
What is this service? What language is it written into? Doesn't the language used to write this service support JSON? Is it an OOP language? Are you saying that the service is manipulating strings directly?
Darin Dimitrov
@Darin - yes, strings directly and outside of my control.
Kevin Montrose
+1  A: 

I followed the JsonConvert.SerializeObject(key) method call via reflection (where key was an IList) and found that JsonSerializerInternalWriter.SerializeList gets called. It takes a list and loops through via

for (int i = 0; i < values.Count; i++) { ...

where values is the IList parameter brought in.

Short answer is...No, there's no built in way to set the order the fields are listed in the JSON string.

DougJones