0

How i can convert diction list to json ?

struct User: Codable {
    var id = ""
    var deviceName = ""
}
    var userList:[Any] = []
    for user in users {
        var b : [String: Any] = [:]
        b["name"] = user.deviceName
        b["id"] = user.id
        //        b["uuid"] = user.uuid.uuidString
        userList.append(b)
        
    }
    print(JSONSerialization.isValidJSONObject(userList))
    
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: userList, options: .prettyPrinted)
        return .ok(.json(jsonData))
    } catch {
        return .ok(.htmlBody("Error"))
    }

terminating with uncaught exception of type NSException *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSConcreteUUID)' terminating with uncaught exception of type NSException

Wang Liang
  • 4,244
  • 6
  • 22
  • 45

1 Answers1

1

You can use the Codable to easily encode and decode your object and JSONs:

do {
    let jsonEncoder = JSONEncoder()
    let jsonData = try jsonEncoder.encode(users)
    ,,,
} catch {
    print(error)
    return .ok(.htmlBody("\(error.localizedDescription)"))
}

Some side notes:

  1. Always try print out the real error instead of throwing a simple string.
  2. Catch means there where an error. So you may consider returning a badRequest or something instead of ok.

It seems like you need to pass a JSON. So you can convert the jsonData to a jsonObject like:

    let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
    print(JSONSerialization.isValidJSONObject(jsonObject)) // <- to verify
    return .ok(.json(jsonObject))
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278