tristanhimmelman / ObjectMapper

Simple JSON Object mapping written in Swift
MIT License
9.13k stars 1.03k forks source link

Object converting to JSON is not working properly (Object.toJSON() or Object.toJSONString(prettyPrint: true)) #1124

Open smeet-chavda opened 2 years ago

smeet-chavda commented 2 years ago

Hello,

Greetings of the day!

First of all thanks for this wonderful library, I like it. 🙂

I just want to write an issue which I am facing, I work as an iOS developer and this issue occurs with Xcode-swift.

I am trying to upload media in bytes to API, let me explain it step by step:-

  1. Created blank mappable object for e.g. let object = WorkOrderRequest(JSON: [:])
  2. Added data to object for e.g. object.subJobID = 2 and other data accordingly.

Example:- let attachment: WorkOrderAttachments? attachment.MimeType = "ApplicationPDF" attachment.FileName = "Name" attachment.Media = Image object in bytes(Data)

assign that to 'object.WorkOrderAttachments = [attachment]'

Until here everything works fine, even I can extract each specific object(Media object as well).

  1. Now when I try to upload it to API, I have to convert the object to JSON and pass it to the API. but somehow converting gets failed. I can see all the other objects in JSON except 'Media' somehow it gets lost or not converted.

Your help is much appreciated. Looking forward to hearing from you guys soon. TIA

Your JSON dictionary:

[ "SubJobID": 2, "WorkOrderAttachments": [ { "MimeType": MimeType.ApplicationPDF, "FileName": "WorkAuthorizationEmergency_08252021_1.pdf", "Media": 3028bytes } ], "WoStatus": 1 ]

Your model:

class NewWorkOrderRequest: NSObject, Mappable { var subJobID : Int64? var woStatus : Int64? var workOrderAttachments : [WorkOrderAttachments]?

required init? (map: Map) {
}

func mapping(map: Map) {
    subJobID <- map["SubJobID"]
    woStatus <- map["WoStatus"]
    workOrderAttachments <- map["WorkOrderAttachments"]
}

}

class WorkOrderAttachments: NSObject, Mappable {

var media : Data?
var fileName : String?
var mimeType : MimeType?

required init? (map: Map) {
}

func mapping(map: Map) {
    media <- map["Media"]
    mimeType <- map["MimeType"]
    fileName <- map["FileName"]
}

}

What you did:

Data imported to object correctly, but while converting it to JSON, 'Media' object gets null and not passed to API.

For e.g.:- 'Object.toJSON()'

after converting, the result is like:-

[ "WoStatus": 1, "SubJobID": 2, "WorkOrderAttachments": [ { "MimeType": "application/pdf", "FileName": "WorkAuthorizationEmergency_08252021_1.pdf" } ] ]

What you expected:

I expected something like:

Convert from Mappable object to JSON or JSONString is not working properly and data of object gets lost.