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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改