Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

ios - How to convert stored values to JSON format using Swift?

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

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

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...