我有一个结构数组,我需要写入服务器端代码,我似乎无法找到添加带有多个父键的json对象的任何示例。
struct Photo {
var imageName = "", thumbFileURL = "", viewCount = 0, likeCount = 0
}
然后我有一些照片对象声明为......
var photo1 = Photo()
photo1.imageName = "ImPhoto1"
photo1.thumbFileURL = "www.SO.com"
photo1.viewCount = 5
photo1.likeCount = 1
var photo2 = Photo()
photo1.imageName = "ImPhoto2"
photo1.thumbFileURL = "www.SO.com"
photo1.viewCount = 10
photo1.likeCount = 2
////// and then same for x amount of Photo() object
然后我有一个数组
myArray = [photo1,photo2,photo3, ...]
然后我需要写一个看起来像这样的json:
myJson object = {
photo1: {
imageName: "ImPhoto1"
thumbFileURL = "www.SO.com"
viewCount: 5
likeCount: 1
},
photo2: {
imageName: "Imphoto2"
....
},
....
}
所以我的问题是,如何转换myarray
- > myJson
答案 0 :(得分:2)
您需要Encodable
PhotoCollection
的自定义实现,这是一组照片的包装类型:
struct Photo : Codable {
var imageName = "", thumbFileURL = "", viewCount = 0, likeCount = 0
}
struct PhotoCollection: Encodable, ExpressibleByArrayLiteral {
var photos: [Photo]
typealias ArrayLiteralElement = Photo
init(arrayLiteral elements: Photo...) {
photos = elements
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
for (i, photo) in photos.enumerated() {
try container.encode(photo, forKey: CodingKeys(stringValue: "photo\(i + 1)")!)
}
}
struct CodingKeys: CodingKey, ExpressibleByStringLiteral {
var stringValue: String { return key }
init?(stringValue: String) {
key = stringValue
}
var intValue: Int? { return Int(key) }
init?(intValue: Int) {
key = "\(intValue)"
}
init(stringLiteral value: String) {
key = value
}
var key: String
}
}
var photo1 = Photo()
photo1.imageName = "ImPhoto1"
photo1.thumbFileURL = "www.SO.com"
photo1.viewCount = 5
photo1.likeCount = 1
var photo2 = Photo()
photo1.imageName = "ImPhoto2"
photo1.thumbFileURL = "www.SO.com"
photo1.viewCount = 10
photo1.likeCount = 2
let photoCollection: PhotoCollection = [photo1, photo2]
let json = try JSONEncoder().encode(photoCollection)
print(String(data: json, encoding: .utf8)!)
打印:
{"photo2":{"imageName":"","likeCount":0,"viewCount":0,"thumbFileURL":""},"photo1":{"imageName":"ImPhoto2","likeCount":2,"viewCount":10,"thumbFileURL":"www.SO.com"}}
格式化:
{
"photo2": {
"imageName": "",
"likeCount": 0,
"viewCount": 0,
"thumbFileURL": ""
},
"photo1": {
"imageName": "ImPhoto2",
"likeCount": 2,
"viewCount": 10,
"thumbFileURL": "www.SO.com"
}
}
答案 1 :(得分:0)
struct Photo:Codable {
var imageName = "", thumbFileURL = "", viewCount = 0, likeCount = 0
}
var photo1 = Photo()
photo1.imageName = "ImPhoto1"
photo1.thumbFileURL = "www.SO.com"
photo1.viewCount = 5
photo1.likeCount = 1
var photo2 = Photo()
photo1.imageName = "ImPhoto2"
photo1.thumbFileURL = "www.SO.com"
photo1.viewCount = 10
photo1.likeCount = 2
var myArray = [photo1,photo2]
let tempData = try? JSONEncoder().encode(myArray)
//Create JSON
var Finaldata: Any?
if let data = tempData { Finaldata = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) }
这将工作