Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 
 80-c 
 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"
????????}
????]
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
177 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...