0
class LeadsEntity: NSObject, Mappable {
var name: String?
var mobile: String?
var address: String?
var coords: String?
var stime: String?

override init() {}

required init?(map: Map) {}

func mapping(map: Map) {
    name <- map["name"]
    mobile <- map["mobile"]
    address <- map["address"]
    coords <- map["coords"]
    stime <- map["stime"]
}
}

I am using this method to convert model to json string

func json(from object: Any) -> String? {
    let JSONString = (object as! [LeadsEntity]).toJSONString(prettyPrint: true)?.replacingOccurrences(of: "\n", with: "").replacingOccurrences(of: "    ", with: "")
    return JSONString
}

but it converts like this enter image description here

I am not able to remove \ and I also tried to remove by .replacingOccurrences(of: "\", with: "", options: NSString.CompareOptions.literal, range:nil) but no success. Thanks in advance.

Rahul Gupta
  • 501
  • 1
  • 7
  • 15
  • 3
    The backslashes are virtual (not real) to be able to display doubles quotes in a string literal. By the way since the introduction of Codable `ObjectMapper` has become obsolete. – vadian Jun 11 '22 at 09:39
  • @vadian But when i am sending to server side it is not accepted. – Rahul Gupta Jun 11 '22 at 09:41
  • Remove also the pretty print option. This avoids the.whitespace and the server doesn’t care anyway.. And don’t send an optional. And ~ again ~ drop ObjectMapper in favor of Codable. – vadian Jun 11 '22 at 09:43
  • I have removed pretty option it looks like this "[{\"name\":\"Testing \",\"stime\":\"03:15 PM\",\"mobile\":\"7654346782\",\"address\":\"Test\",\"coords\":\"0.0000,0.000\"},{\"coords\":\"0.0000,0.000\",\"address\":\"Test\",\"mobile\":\"7654346782\",\"stime\":\"03:15 PM\",\"name\":\"Testing \"}]" – Rahul Gupta Jun 11 '22 at 09:50
  • 1
    That’s perfect. Assign the string to a label and the backslashes are gone. – vadian Jun 11 '22 at 09:52
  • 1
    You did print the values with the help of the debugguer. A little tips: `po JSONString`; `po JSONString!`; `po print(JSONString)`; `po print(JSONString!)` will give different output, depending on your needs. – Larme Jun 11 '22 at 10:19

1 Answers1

0

Give him the model here (type: T.self) and put the Data here (from: data)

do {
     let decoded = self.decodeJSON(type: T.self, from: data)
   } catch {}

func decodeJSON<T: Decodable>(type: T.Type, from: Data?) -> T? {
        let decoder = JSONDecoder()
        guard let data = from else { return nil }
        do {
            let objects = try decoder.decode(type.self, from: data)
            
            return objects
        } catch let jsonError {
            print("Failed to decode response JSON", jsonError)
            return nil
        }
    }
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
Alex
  • 1
  • 3