【发布时间】:2016-09-24 21:09:01
【问题描述】:
我会尽量详细回答这个问题。
首先,我在代码中定义了以下结构:
struct LogInfo {
var logNumber: Int
var species: String
var diameter: Float
var formClass: Int
var numLogs: Float
var boardFootage: Double
static func jsonArray(array : [LogInfo]) -> String {
return "[" + array.map {$0.jsonRepresentation}.joinWithSeparator(",") + "]"
}
var jsonRepresentation : String {
return "{\"logNumber\":\"\(logNumber)\",\"species\":\"\(species)\",\"diameter\":\"\(diameter)\",\"formClass\":\"\(formClass)\",\"numLogs\":\"\(boardFootage)\"}"
}
}
这基本上创建了已定义结构的 JSON 表示。
在我的代码的另一部分,我正在用以下内容组成一个 JSON 字符串:
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
guard let URL = NSURL(string: "http://logster.dynamiscms.com/jsonTest.php") else {return}
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "POST"
// Headers
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
//Get the JSON Array from the Struct
let jsonArray = LogInfo.jsonArray(logArray)
// Compose the JSON Body
let bodyObject = [
"propertyOwner": "\(propertyOwner)",
"propertyID": "\(propertyID)",
"scaledBy": "\(scaledBy)",
"acres": "\(acres)",
"notes": "\(notes)",
"logDetails": jsonArray
]
到目前为止,所有内容基本上都需要 5 个变量,这些变量被传递到我的 segue,然后附加在结构中准备好的 JSON。
我想将我编译的 JSON 传递给 PHP 脚本,然后该脚本将解析该 JSON 并最终将其存储到数据库中。
我的代码没有出现任何错误 - 但 JSON 没有正确准备,这导致我无法在 PHP 中解析它。
基于此代码,我能够使用 PHP 解析前五个值(propertyOwner、propertyID、scaledBy、acres 和 notes)。但是,当我进入详细信息数组时,我无法进入那些嵌套值。
看起来当我将它传递到我的 PHP 脚本时,它会将其作为 JSON 吐出(我意识到这不是有效的 JSON):
[
"notes": "This is a test.",
"propertyID": "Beam Residence",
"acres": "1",
"scaledBy": "Andy Spencer",
"propertyOwner": "Jim Beam",
"logDetails": "
{\"logNumber\":\"1\",\"species\":\"White Pine\",\"diameter\":\"18.0\",\"formClass\":\"78\",\"numLogs\":\"124.56227\"},
{\"logNumber\":\"2\",\"species\":\"Hemlock\",\"diameter\":\"17.0\",\"formClass\":\"78\",\"numLogs\":\"147.0589725\"},
{\"logNumber\":\"3\",\"species\":\"Spruce\",\"diameter\":\"21.0\",\"formClass\":\"82\",\"numLogs\":\"335.9106016\"}"
]
有人能帮我弄明白我缺少什么吗?
【问题讨论】:
标签: php arrays json swift xcode