Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize or convert Swift objects to JSON?

Tags:

json

swift

This below class

class User: NSManagedObject {   @NSManaged var id: Int   @NSManaged var name: String } 

Needs to be converted to

{     "id" : 98,     "name" : "Jon Doe" } 

I tried manually passing the object to a function which sets the variables into a dictionary and returns the dictionary. But I would want a better way to accomplish this.

like image 911
Penkey Suresh Avatar asked Apr 13 '15 06:04

Penkey Suresh


People also ask

What is JSON serialization in Swift?

Swift version: 5.6. If you want to parse JSON by hand rather than using Codable , iOS has a built-in alternative called JSONSerialization and it can convert a JSON string into a collection of dictionaries, arrays, strings and numbers in just a few lines of code.

Can JSON be serialized?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

What is Swifty JSON in Swift?

SwiftyJSON is a library that helps to read and process JSON data from an API/Server. So why use SwiftyJSON? Swift by nature is strict about data types and wants the user to explicitly declare it. This becomes a problem as JSON data is usually implicit about data types.

What is JSON parsing in Swift?

JSON parsing in Swift is a common thing to do. Almost every app decodes JSON to show data in a visualized way. Parsing JSON is definitely one of the basics you should learn as an iOS developer. Decoding JSON in Swift is quite easy and does not require any external dependencies.


1 Answers

In Swift 4, you can inherit from the Codable type.

struct Dog: Codable {     var name: String     var owner: String }  // Encode let dog = Dog(name: "Rex", owner: "Etgar")  let jsonEncoder = JSONEncoder() let jsonData = try jsonEncoder.encode(dog) let json = String(data: jsonData, encoding: String.Encoding.utf16)  // Decode let jsonDecoder = JSONDecoder() let secondDog = try jsonDecoder.decode(Dog.self, from: jsonData) 
like image 99
Etgar Avatar answered Sep 30 '22 17:09

Etgar