gpt4 book ai didi

php - Swift 对象数组转 JSON -> POST -> PHP json_decode() 转 PHP 对象数组

转载 作者:行者123 更新时间:2023-11-30 12:33:15 36 4
gpt4 key购买 nike

我已经写 swift/php/sql 3 个月了......(我知道我是一个菜鸟)。我可以创建简单的 POST 字符串并发出 http 请求...等等。
现在我正在尝试将多个对象推送到我的服务器以添加到我的数据库中。所以我认为传输对象的最佳方法是使用大的 json 字符串。也许不是……我不知道。我未能成功创建要发布的多个对象 json 字符串。理想情况下,我想要一个 PHP json_decode($myJsonString) 将直接解码的字符串...我创建了一个 Playground 来用作测试用例。对 JSON(myPlaceArray) 的调用导致“未知”。
欢迎提出有关如何解决此问题或更简单的方法的建议!谢谢!

import UIKit
import SwiftyJSON
class myClass {

public struct Place {
var PlaceId = String()
var name = String()
var address = String()
var latitude = Double()
var longitude = Double()
}

}

var myPlaceArray = [myClass.Place()]
var myPlace = myClass.Place()

for i in 0..<3 {
myPlace.PlaceId = "\(i)"
myPlace.address = "My Address \(i)"
myPlace.name = "My Name \(i)"
myPlace.latitude = 37.123
myPlace.longitude = -127.321
if(i==0){
myPlaceArray[0] = myPlace
}
else {
myPlaceArray.append(myPlace)
}
}
print(myPlaceArray[0])

let json = JSON(myPlaceArray)
print(json) // results: "unknown"

let jsonMyPlaceArray = JSON(myPlaceArray)
print(jsonMyPlaceArray)

//setup json post data

//send HTTP POST
let myUrl = NSURL(string: "https://myUrl.php")
let request = NSMutableURLRequest(url: myUrl! as URL)
request.httpMethod = "POST"
let postString = "jsonPlaces=\(String(describing: jsonMyPlaceArray))"

print(postString) // jsonPlaces=unknown

//.... make request

playground_image

最佳答案

我发现 JSONUtils 非常有用: https://github.com/peheje/JsonSerializerSwift您可以将消息建模为 Swift 类,然后使用此库将它们序列化。这是我发布包含文本数据和编码图像的 JSON 消息的一段代码:

TeamsSao 类:BaseSao {

class func update ( request : TeamUpdateRequest, callback : @escaping (TeamUpdateResponse!) -> Void ) {

var strUrl : String = getServiceUrl() + "/index.php"
strUrl += "?avoid_cache=" + StringUtils.randomString (length: 24)

let url: URL = URL(string: strUrl)!

var urlRequest: URLRequest = URLRequest(url: url)

urlRequest.httpMethod = "POST"
urlRequest.timeoutInterval = 120000
urlRequest.cachePolicy = .reloadIgnoringLocalCacheData

urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")

let bodyStr:String = "msg=" + JSONUtils.toJson(request)//"pseudo=test"
urlRequest.httpBody = bodyStr.data(using: String.Encoding.utf8)

let session = URLSession.shared

session.dataTask(with: urlRequest, completionHandler:
{ (data, response, error) in

//print(data)
//print(response)
//print(error)

var result : TeamUpdateResponse!

if (error == nil) {
if let httpResponse = response as? HTTPURLResponse {
if (httpResponse.statusCode < 200) || (httpResponse.statusCode >= 300) {
result = TeamUpdateResponse()
result.status = TeamUpdateResponse.RESULT_EXCEPTION
result.errorDescription = "Response Status: \(httpResponse.statusCode)"
} else {
result = TeamUpdateParser.parse(data: data!)
}
}

} else {
//print("A connection error occurred, here are the details:\n \(error)")
result = TeamUpdateResponse()
result.status = TeamUpdateResponse.RESULT_EXCEPTION
result.errorDescription = error as! String!
}
callback (result)
}
).resume()

}

}

需要理解的几点:

  1. TeamUpdateRequest 是包含要发送的数据的类
  2. TeamUpdateResponse 是包含响应的类
  3. 使用 Swift 3,您应该使用回调函数。该方法接收一个回调函数,因此,当发布完成时,将解析响应,然后调用回调。

关于php - Swift 对象数组转 JSON -> POST -> PHP json_decode() 转 PHP 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43190753/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com