2

Scenario: I have a schemaless database API that infers type based on json passed into it. Once the database infers schema however, all subsequent entries added to the same table must follow the existing schema. I'm pushing json-formatted data to a REST endpoint from my Swift app.

I'm using ObjectMapper to define schema/serialization for data within the Swift app, e.g.:

class ExampleDatum: Mappable {

    value: Float?

    init() {
    }

    required init?(map: Map) {
    }

    func mapping(map: Map) {
        value <- map["value"]
    }
}

The issue comes that if value is a whole number, json is formatted without the decimal point, leading to inconsistent interpretation of this field as an integer/float:

let datum = ExampleDatum()
datum.value = 5.0
print(datum.toJSONString())
>> {"value": 5}

What's the best practice to embed this type information in JSON, e.g. to enforce the decimal point always be included? Ideally something like {"value": 5.0}

Ben Lieber
  • 113
  • 1
  • 7
  • I'm supprised that this even compiles. The designated initiliazer for that framework is `ExampleDatum(JSON: [String: Any])`. That way your float will be processed by the built in mapper. Maybe that would solve your problem? – Desdenova May 03 '17 at 16:11
  • Sorry forgot default constructor, fixed in code example above. But the issue here is for serialization from float to the mapped json – Ben Lieber May 03 '17 at 18:50

1 Answers1

0

Try

let value = 5.0
let float_string = String(format: "%#f", value)
Scott Thompson
  • 22,629
  • 4
  • 32
  • 34
  • This is close - tried using [custom transformations](https://github.com/Hearst-DD/ObjectMapper#custom-transforms) e.g. `(map["value"], TransformOf(fromJSON: { Float($0!) }, toJSON: { $0.map { String(format: "%#f", $0) } }))` - the issue is this serializes as a string and is inferred as a string rather than a number by database endpoint – Ben Lieber May 03 '17 at 19:21