duanjuan1103 2017-04-03 17:25
浏览 88
已采纳

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

I've been writing swift/php/sql for 3 months now... (I know I'm a rookie). I can create simple POST strings and issue http requests... etc.
Now I'm trying to push multiple objects to my server to add to my database. So I'm thinking the best way to transport the objects is to use a big json string. Maybe not... idk. I have been unsuccessful at creating the multiple object json string to post. Ideally, I'd like a string that PHP json_decode($myJsonString) will decode directly... I've created a playground to use as a test case. The call to JSON(myPlaceArray) results in "unknown".
Suggestions on how fix this or and easier way welcome! thank you!

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

  • 写回答

1条回答 默认 最新

  • douhui8163 2017-04-03 17:40
    关注

    I found very useful the JSONUtils: https://github.com/peheje/JsonSerializerSwift You can model your message as Swift classes and later serialize them using this library. This is a piece of the code where I post a JSON message containing text data and an encoded image:

    class 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:
     \(error)")
                    result  = TeamUpdateResponse()
                    result.status = TeamUpdateResponse.RESULT_EXCEPTION
                    result.errorDescription = error as! String!
                }
                callback (result)
        }
            ).resume()
    
    }
    

    }

    A few points to understand:

    1. TeamUpdateRequest is the class containing the data to send
    2. TeamUpdateResponse is the class containing the response
    3. With Swift 3 the you should work with callback functions. This method receive a callback function so, when the post is completed, the response will be parse and then the callback called.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条