Ryan B.
Ryan B.

Reputation: 99

convert struct array to json swift

I have an array of struct's that I need to write to a server side code, I can't seem to find any examples of adding a json object with multiple parent keys.

struct Photo {
    var imageName = "", thumbFileURL = "", viewCount = 0, likeCount = 0
}

and then I have a couple of photo object that are declared like...

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

And then I have an array

myArray = [photo1,photo2,photo3, ...]

and then I need to write a json that looks something ike this:

myJson object = {
    photo1: {
        imageName: "ImPhoto1"
        thumbFileURL = "www.SO.com"
        viewCount: 5
        likeCount: 1
    },
    photo2: {
        imageName: "Imphoto2"
        ....
    },
    ....
}

so my question is, how do I convert myarray -> myJson

Upvotes: 1

Views: 3141

Answers (2)

Sweeper
Sweeper

Reputation: 275125

You need a custom implementation of Encodable of PhotoCollection, which is a wrapper type for an array of photos:

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)!)

This prints:

{"photo2":{"imageName":"","likeCount":0,"viewCount":0,"thumbFileURL":""},"photo1":{"imageName":"ImPhoto2","likeCount":2,"viewCount":10,"thumbFileURL":"www.SO.com"}}

Formatted:

{
  "photo2": {
    "imageName": "",
    "likeCount": 0,
    "viewCount": 0,
    "thumbFileURL": ""
  },
  "photo1": {
    "imageName": "ImPhoto2",
    "likeCount": 2,
    "viewCount": 10,
    "thumbFileURL": "www.SO.com"
  }
}

Upvotes: 2

Amey
Amey

Reputation: 815

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

This Will Work

Upvotes: 0

Related Questions