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

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.
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题