简体   繁体   English

在Swift 4中创建特定的Json

[英]Create specific Json in Swift 4

I have to deliver some specific JSON to a webserver, but I'm very confused about how to use the correct arrays and dictionaries, so I can't get to my final result. 我必须将一些特定的JSON传递到Web服务器,但是我对如何使用正确的数组和字典感到非常困惑,因此无法获得最终结果。 I'm starting from this: 我从这个开始:

["entries": [
              "member" : [
                          "id" : key,
                          "name" : value
                          ],
              "timestamp" : "\(dateString)"
              ]
]

in the JSON file I have to send to the server I can only have 1 "entries" and several "member" with specific "id" and "name" and timestamp. 在我必须发送到服务器的JSON文件中,我只能有1个“条目”和几个具有特定“ id”和“ name”以及时间戳的“ member”。 I'm aware that I have to use dictionaries but can't get to this result. 我知道我必须使用字典,但无法获得此结果。 This is what I tried so fare: 这是我尝试过的票价:

var leden = [Int: String]()
var jsonDict = [String: Any]()
var dateString = Date()

for (key, value) in leden{

        jsonDict["\(key)"] = ["member" : [
                                          "id" : key,
                                          "naam" : value
                                          ],
                              "timestamp" : "\(dateString)"
                             ]
    }
    jsonFinaal = ["entries": jsonDict]

this is as close as I could get, but good enough because the key in jsonDict should not be there, I added the "entries" in a second dictionary to make this a unique entry. 这与我能得到的差不多,但是足够好了,因为jsonDict中的键不应该存在,我在第二个字典中添加了“条目”以使其成为唯一的条目。

Anyone who can do beter to help me to the solution? 谁能做得更好以帮助我解决问题?

The value for members is an array of dictionaries, not a dictionary members的值是字典数组 ,而不是字典

This creates the structure sorted by the id keys 这将创建按id键排序的结构

let leden = [1 : "Foo", 2: "Bar"]
let sortedKeys = leden.keys.sorted()
let dateString = Date()

var members = [[String:Any]]()
for key in sortedKeys {
    let naam = leden[key]!
    members.append(["member" : ["id" : key, "naam" : naam], "timestamp" : "\(dateString)"])
}
let entries = ["entries": members]

print(entries)

And the JSON string with 和JSON字符串

do {
    let jsonData = try JSONSerialization.data(withJSONObject: entries)
    let json = String(data: jsonData, encoding: .utf8)
    print(json)
} catch { print(error) }

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

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