sha February 2016

SwiftyJSON order of elements inside JSON object

I'm using SwiftyJSON to serialize/deserialize JSON data when communicating with EntityFramework backend. Problem is - for some endpoints EF expects to see "__type" attribute to properly map it to .NET class in the backend. And this "__type" attribute must be very first attribute of the JSON object.

Here are example of working payload:

"changeSet" : [
    {
      "OriginalEntity" : {
        "__type" : "outside_vendors_to_events:#QPWebOffice.Web",
        "revenue" : 0,
        "transactions_count" : 23,
        "id" : 8,
        "vendor" : "New",
        "event_id" : 4
      },
      "Operation" : 3,
      "Entity" : {
        "__type" : "outside_vendors_to_events:#QPWebOffice.Web",
        "revenue" : 0,
        "transactions_count" : 2,
        "id" : 8,
        "vendor" : "New",
        "event_id" : 4
      },
      "Id" : 0
    }
  ]

That works fine. But if for some reason __type will get move lower in the object - server fails. Now, I know that you can't guarantee order of elements in dictionary, but how else that can be worked out?

I'm creating JSON object in Swift like this:

return JSON([
    "__type": "outside_vendors_to_events:#QPWebOffice.Web",
    "event_id": eventId,
    "id": id,
    "revenue": revenue,
    "transactions_count": transactionCount,
    "vendor": name == nil ? NSNull() : name!
])

The order seems to be same always, but it's different for different classes I have in the app. And for some of them - regardless of what I do - "__type" will end up in the middle of JSON properties.

Any idea would be greatly appreciated. And no, I can't change server.

Answers


David Berry February 2016

Dictionaries are, by design, not stable on insertion order (insertion order doesn't matter when iterating keys) EF is arguably broken in requiring order of JS objects, which also isn't specified. That said, you might be able to solve the problem using something like the answers to this question: Insertion-Order Dictionary (like Java's LinkedHashMap) in Swift?. Barring that, you'll need to customize your serialization operation (whatever turns your Dictionary into JSON) to special case this.

Post Status

Asked in February 2016
Viewed 3,638 times
Voted 8
Answered 1 times

Search




Leave an answer