3

Xcode 8 でSiestaと Swift 3を使用して API クライアントを構築しpatchています。

問題は、エンティティがあることです。JSON 配列をエンティティ フィールドに保存すると、それらをサーバーに送り返すことができず、次のエラーが発生します。

▿ Siesta.RequestError
  - userMessage: "Cannot send request"
  - httpStatusCode: nil
  - entity: nil
  ▿ cause: Optional(Siesta.RequestError.Cause.InvalidJSONObject())
    - some: Siesta.RequestError.Cause.InvalidJSONObject
  - timestamp: 502652734.40489101

私のエンティティは:

import SwiftyJSON
import Foundation
struct Order {
    let id: String?
    let sessionId: String?
    let userId: Int?
    let status: String?
    let comment: String?
    let price: Float?
    let products: Array<JSON>? 

    init(json: JSON) throws {
        id          = json["id"].string
        sessionId      = json["sessionId"].string
        userId      = json["userId"].int
        status        = json["status"].string
        comment        = json["comment"].string
        price       = json["price"].float
        products   = json["products"].arrayValue

    }

    /**
     * Helper method to return data as a Dictionary to be able to modify it and do a patch
     **/
    public func toDictionary() -> Dictionary<String, Any> {
        var dictionary: [String:Any] = [
            "id": id ?? "",
            "sessionId": sessionId ?? "",
            "userId": userId ?? 0,
            "status": status ?? "",
            "comment": comment ?? ""
        ]
        dictionary["products"] = products ?? []

        return dictionary
    }
}

私がやっていることは次のとおりです。

 MyAPI.sessionOrders(sessionId: sessionId).request(.post, json: ["products": [["product": productId, "amount": 2]], "comment": "get Swifty"]).onSuccess() { response in
    let createdObject : Order? =  response.typedContent()
    expect(createdObject?.sessionId).to(equal(sessionId))
    expect(createdObject?.comment).to(equal("get Swifty"))
    expect(createdObject?.products).to(haveCount(1))
    expect(createdObject?.price).to(equal(product.price! * 2))

    if let createdId = createdObject?.id {
        var data = createdObject?.toDictionary()
        data?["comment"] = "edited Swifty" // can set paid because the user is the business owner
        MyAPI.order(id: createdId).request(.patch, json: data!).onSuccess() { response in
            result = true

        }.onFailure() { response in
                dump(response) //error is here
        }
    }
}

資力:

func sessionOrders( sessionId: String ) -> Resource {
    return self
        .resource("/sessions")
        .child(sessionId)
        .child("orders")
}
func order( id: String ) -> Resource {
    return self
        .resource("/orders")
        .child(id)
}

変圧器:

    self.configureTransformer("/sessions/*/orders", requestMethods: [.post, .put]) {
        try Order(json: ($0.content as JSON)["data"])
    }

    self.configureTransformer("/orders/*") {
        try Order(json: ($0.content as JSON)["data"])
    }

次のような辞書構造を作成することで、これを回避することができました。

let products: Array<Dictionary<String, Any>>?

    products   = json["products"].arrayValue.map({
        ["product": $0.dictionaryValue["product"]!.stringValue, "amount": $0.dictionaryValue["amount"]!.intValue]
    })

しかし、何かを変更する必要がある場合、私はダウンキャストの地獄に住んでいます。

var data = createdObject?.toDictionary()
data?["comment"] = "edited Swifty" 
//if I want to modify the products...
var products = data?["products"] as! Array<Dictionary<String, Any>>
products[0]["amount"] = 4
data?["products"] = products

元の JSON 配列を Siesta で送信するにはどうすればよいですか? 変更や読み取りが非常に簡単です。シエスタのドキュメントとgithubの問題を閲覧しましたが、成功しませんでした...

4

1 に答える 1