Perfect icon indicating copy to clipboard operation
Perfect copied to clipboard

Error encoding array of Encodable

Open jwelton opened this issue 6 years ago • 6 comments

Hello 👋

Not sure if this is expected or already a know issue, but I couldn't find anything in "issues". In a simplistic example, if you pass an Encodable object to setBody, then it encodes into JSON and returns the payload as expected. If however you change this so you're returning a array literal of Encodable's, then you get the following error:

The operation couldn’t be completed. (PerfectLib.JSONConversionError error 0.)

As it's an array of Encodable's, I would have expected the array to become Encodable too? As array normally gains this conformance automatically if all its elements are Encodable.

Here is a simple code example of the problem:

import PerfectHTTP
import PerfectHTTPServer

struct Foo: Encodable {
    let bar: String
}

var routes = Routes()

routes.add(method: .get, uri: "/hello") { request, response in
    do {
        try response.setBody(json: [Foo(bar: "Hello World")]) // This line throws an error. However passing Foo(bar: "Hello") would process fine
        response.completed(status: .ok)
    } catch {
        print(error.localizedDescription)
        response.setBody(string: "Internal Server Error")
        response.completed(status: .internalServerError)
    }
}

try HTTPServer.launch(name: "localhost",
					  port: 8181,
					  routes: routes,
					  responseFilters: [
						(PerfectHTTPServer.HTTPFilter.contentCompression(data: [:]), HTTPFilterPriority.high)])

jwelton avatar Jul 12 '19 10:07 jwelton

sorry if i am wrong let me try to help try response.setBody(json: [Foo(bar: "Hello World")]) is this asking you JSON ? formate -> json: [Foo(bar: "Hello World")] but you give me -> Foo(bar: "Hello World") you got the point try to convert struct json

saroar avatar Jul 12 '19 11:07 saroar

Sorry not sure I will understand @saroar. Are you asking if passing Foo(bar: "Hello World") not as part of an array literal works? I.e.

try response.setBody(json: Foo(bar: "Hello World"))

If so, then yes it does work on its own. Only when passed inside an array literal does it then fail to parse into JSON.

jwelton avatar Jul 12 '19 11:07 jwelton

static func create(data: [String:Any]) throws -> RequestHandler {
        return { (request, response) in
            let contextAuthenticated = !(request.session?.userid ?? "").isEmpty
            if !contextAuthenticated { return response.redirect(path: "/login") }
            
            if contextAuthenticated {

                do {
                    
                    let decodeMessage = try request.decode(Message.self)
                    
                    let message = Message(
                        id: UUID().uuidString,
                        eventId:    decodeMessage.eventId,
                        senderID:    decodeMessage.senderID,
                        receiverID:  decodeMessage.receiverID,
                        text:        decodeMessage.text,
                        type:        decodeMessage.type,
                        status:      decodeMessage.status,
                        cmd:         decodeMessage.cmd,
                        imageWidth:  decodeMessage.imageWidth,
                        imageHeight: decodeMessage.imageHeight,
                        timestamp:   decodeMessage.timestamp
                    )
                    
                    let db = try getDB()
                    let messageTable = db.table(Message.self)
                    try messageTable.insert(message)
                    
                    let data = message.jsonData
                    let anyResult: Any = try JSONSerialization.jsonObject(with: data!, options: [])
                    let json =  anyResult as? [String: Any]
                    
                    try response.setBody(json: json)
                        .setHeader(.contentType, value: "application/json")
                        .completed()

                } catch {

                    response.setBody(string: "Errors: \(error)").completed(status: .internalServerError)

                }
            }
        }
    }

my working code

saroar avatar Jul 12 '19 11:07 saroar

check this one too

static func create(data: [String: Any]) throws -> RequestHandler {
        return { (request, response) in
            
            let contextAuthenticated = !(request.session?.userid ?? "").isEmpty
            if !contextAuthenticated {
                return response.redirect(path: "/login")
            }
            
            do {
                
                let db = try getDB()
                let callTable = db.table(CallHistory.self)
                try callTable.index(\.receiverID, \.senderID)
                let decodeCall = try request.decode(CallHistory.self)
                
                let creatCall = CallHistory(
                    id: UUID().uuidString,
                    receiverID: decodeCall.receiverID,
                    senderID: decodeCall.senderID,
                    mobileNumber: decodeCall.mobileNumber,
                    duration: decodeCall.duration,
                    isVideoCall: decodeCall.isVideoCall,
                    isOutGoingCall: decodeCall.isOutGoingCall,
                    createAt: decodeCall.createAt,
                    updateAt: decodeCall.updateAt
                )
                
                try callTable.insert(creatCall)
                
                response.setBody(string: creatCall.jsonString ?? "")
                    .setHeader(.contentType, value: "application/json")
                    .completed()

            }
                
            catch {
                response.setBody(
                    string: "Errors: \(error)")
                    .completed(status: .internalServerError
                )
            }
        }
    }

@jwelton

saroar avatar Jul 12 '19 11:07 saroar

@saroar thank you for your input, however your code is doing something quite different to the problem I'm trying to explain.

Essentially I'm saying when an array's elements all conform to Codable, the array itself should conform to Codable. This means, passing [Codable] should (from my understanding) be parsed into JSON perfectly fine, however I get errors instead.

You're right in saying you can pass a dictionary of String : Any. But that's not the problem I'm trying to solve here.

jwelton avatar Jul 21 '19 17:07 jwelton

@jwelton what are you trying to solve?

saroar avatar Jul 22 '19 04:07 saroar