0

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.

sha
  • 17,824
  • 5
  • 63
  • 98

1 Answers1

1

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.

Community
  • 1
  • 1
David Berry
  • 40,941
  • 12
  • 84
  • 95
  • 1
    Thanks. Since it's only JSON -> String serialization I ended up manually creating string from my JSON object. I hate it, but it seems to be the simplest way out of this mess. – sha Feb 09 '16 at 23:15
  • 1
    When dealing with broken technologies, often it's best to be pragmatic :) – David Berry Feb 10 '16 at 00:19