简体   繁体   English

需要帮助从混合来源为PHP准备Swift中的JSON

[英]Need help preparing JSON in Swift from mixed sources for PHP

I will try to be as thorough as possible with this question. 在这个问题上,我会尽量做到透彻。

To start, I have the following struct defined in my code: 首先,我在代码中定义了以下结构:

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)\"}"
    }
}

This basically creates a JSON representation of the defined struct. 这基本上会创建已定义结构的JSON表示形式。

In another part of my code, I am composing a JSON string with the following: 在代码的另一部分中,我将使用以下内容组成一个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
]

Everything up to this point basically takes 5 variables that were passed into my segue, and then appends the JSON that was prepared in the struct. 到目前为止,所有内容基本上都接受了传递给我的segue的5个变量,然后追加了在结构体中准备好的JSON。

I want to pass that JSON that I compiled to a PHP script, which will then parse that JSON and eventually store it into a database. 我想将我编译的JSON传递给PHP脚本,然后该脚本将解析该JSON并将其最终存储到数据库中。

I am not getting any errors in my code - but the JSON is not being prepared properly, which is causing me to be unable to parse through it in PHP. 我的代码没有收到任何错误-但JSON的准备不正确,这导致我无法在PHP中通过它进行解析。

Based on this code, I AM able to parse the first five values (propertyOwner, propertyID, scaledBy, acres and notes) with PHP. 基于此代码,我能够使用PHP解析前五个值(propertyOwner,propertyID,scaledBy,英亩和注释)。 However, when I get into the array of details, I cannot get into those nested values. 但是,当我进入细节数组时,便无法进入那些嵌套值。

It looks like when I pass it into my PHP script, it is spitting out this as the JSON (which I realize is not valid JSON): 看起来,当我将其传递到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\"}"

]

Is anybody able to help me make sense of what I am missing? 有人能帮助我弄清我的缺失吗?

Generally, you should not create a JSON String by yourself. 通常,您不应该自己创建JSON字符串。 You need to escape special characters, add " to both ends..., it's not so simple. 您需要转义特殊字符,在两端添加" ...”,这不是那么简单。

And you should not create a string representation of JSON for intermediate values. 并且您不应该为中间值创建JSON的字符串表示形式。 With a slight mistake, the intermediate value is converted to a single JSON String. 稍有错误,中间值将转换为单个JSON字符串。 This is your case. 这是你的情况。

(Your bodyData may be converted to valid JSON, but logDetails in it becomes a single string in PHP, which you do not expect.) (您的bodyData可能会转换为有效的JSON,但是其中的logDetails成为PHP中的单个字符串,这是您所不希望的。)

Change jsonArray(_:) and jsonRepresentation like this: 像这样更改jsonArray(_:)jsonRepresentation

(If you need to use those method and property returning String somewhere else, re-implement them with proper names.) (如果您需要使用在其他地方返回String那些方法和属性,请使用适当的名称重新实现它们。)

static func jsonArray(array : [LogInfo]) -> [AnyObject] {
    return array.map{$0.jsonRepresentation}
}

var jsonRepresentation : [String: AnyObject] {
    return [
        "logNumber": logNumber, //<- or `String(logNumber)`
        "species": species,
        "diameter": diameter, //<- or `String(diameter)`
        "formClass": formClass, //<- or `String(formClass)`
        "numLogs": numLogs, //<- or `String(numLogs)`
        "boardFootage": boardFootage //<- or `String(boardFootage)`
    ]
}

(Many things depends on your PHP side. Usually numeric values are not sent as JSON String to PHP, but if your PHP code needs them as string, you need to enclose numeric values with String(...) .) (许多事情取决于您的PHP端。通常,数字值不作为JSON字符串发送给PHP,但是如果您的PHP代码需要将它们作为字符串,则需要将数字值括在String(...) 。)

And to make your bodyObject : 并使您的bodyObject

let jsonArray = LogInfo.jsonArray(logArray)

let bodyObject: [String: AnyObject] = [
    "propertyOwner": propertyOwner,
    "propertyID": propertyID,
    "scaledBy": scaledBy,
    "acres": acres, //<- or `String(acres)`
    "notes": notes,
    "logDetails": jsonArray
]

Basically you've got multiple errors. 基本上,您有多个错误。 Here is what you want in the end: 最后是您想要的:

{
    "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"}
    ]
}

You get there: 您到达那里:

  1. Change the wrapping brackets to {} 将环绕括号更改为{}
  2. Replace \\" with " 用。。。来代替 ”
  3. Wrap the logDetails with [] and not with "" 用[]而不是用“”来包装logDetails

Let me know if you need help with the code. 让我知道您是否需要代码帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM