How to convert stored values to JSON format using Swift?

久未见 提交于 2020-02-08 10:08:30

问题


I am trying to convert stored coredata values to JSON format and the JSON format value need to assign a single variable, because this generated JSON I need to send to server. Below code I tried to get coredata stored values but don’t know how to generate JSON required format.

Getting values from coredata

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
    do {
        let results = try context.fetch(fetchRequest)
        let  dateCreated = results as! [Userscore]
            for _datecreated in dateCreated {
                print("\(_datecreated.id!)-\(_datecreated.name!)") // Output: 79-b \n 80-c \n 78-a
            }
   } catch let err as NSError {
        print(err.debugDescription)
}

Need to Convert Coredata Value to Below JSON format

{
    "status": true,
    "data": [
        {
            "id": "20",
            "name": "a"
        },
        {
            "id": "21",
            "name": "b"
        },
        {
            "id": "22",
            "name": "c"
        }
    ]
}

回答1:


Probably the easiest is to convert your object(s) to either dictionaries or arrays (depending on what you need).

First you need to be able to convert your Userscore to dictionary. I will use extension on it since I have no idea what your entity looks like:

extension Userscore {

    func toDictionary() -> [String: Any]? {
        guard let id = id else { return nil }
        guard let name = name else { return nil }
        return [
            "id": id,
            "name": name
        ]
    }

}

Now this method can be used to generate an array of your dictionaries simply using let arrayOfUserscores: [[String: Any]] = userscores.compactMap { $0.toDictionary() }.

Or to build up your whole JSON as posted in question:

func generateUserscoreJSON(userscores: [Userscore]) -> Data? {
    var payload: [String: Any] = [String: Any]()
    payload["status"] = true
    payload["data"] = userscores.compactMap { $0.toDictionary() }
    return try? JSONSerialization.data(withJSONObject: payload, options: .prettyPrinted)
}

This will now create raw data ready to be sent to server for instance

var request = URLRequest(url: myURL)
request.httpBody = generateUserscoreJSON(userscores: userscores)



回答2:


You can use the properties of an Encodable to make this happen. This has the added benefit of not resorting to the Any type.

For the JSON, you could use the following types:

struct JSONMessage: Encodable {
    var status: Bool
    var data: [JSONDataEntry]
}

struct JSONDataEntry: Encodable {
    var id: String
    var name: String
}

Then you can adjust your do/try/catch as follows:

do {
    let results = try context.fetch(fetchRequest)
    let  dateCreated = results as! [Userscore]
    // *starting here*
    let data = dateCreated.map { JSONDataEntry(id: String($0.id!), name: $0.name!) }
    let status = true   // <- not sure where status comes from, so adding here
    let message = JSONMessage(status: status, data: data)
    let jsonData = try JSONEncoder().encode(message)
    if let json = String(data: jsonData, encoding: .utf8) {
        // do something with the JSON string
        print(json)
    }
    // *ending here*
} catch let err as NSError {
    print(err.debugDescription)
}


来源:https://stackoverflow.com/questions/59646917/how-to-convert-stored-values-to-json-format-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!