Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 327 Vote(s) - 3.57 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Swift: Convert struct to JSON?

#1
I created a `struct` and want to save it as a JSON-file.

struct Sentence {
var sentence = ""
var lang = ""
}

var s = Sentence()
s.sentence = "Hello world"
s.lang = "en"
print(s)

...which results in:

Sentence(sentence: "Hello world", lang: "en")

But how can I convert the `struct` object to something like:

{
"sentence": "Hello world",
"lang": "en"
}
Reply

#2
Swift 4 introduces the `Codable` protocol which provides a very convenient way to encode and decode custom structs.

struct Sentence : Codable {
let sentence : String
let lang : String
}

let sentences = [Sentence(sentence: "Hello world", lang: "en"),
Sentence(sentence: "Hallo Welt", lang: "de")]

do {
let jsonData = try JSONEncoder().encode(sentences)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString) // [{"sentence":"Hello world","lang":"en"},{"sentence":"Hallo Welt","lang":"de"}]

// and decode it back
let decodedSentences = try JSONDecoder().decode([Sentence].self, from: jsonData)
print(decodedSentences)
} catch { print(error) }

Reply

#3
Here's a nice extension and a method for JSON encoding/decoding:

extension Encodable {

func toJSONString() -> String {
let jsonData = try! JSONEncoder().encode(self)
return String(data: jsonData, encoding: .utf8)!
}

}

func instantiate<T: Decodable>(jsonString: String) -> T? {
return try? JSONDecoder().decode(T.self, from: jsonString.data(using: .utf8)!)
}

Sample usage:

struct Sentence: Codable {
var sentence = ""
var lang = ""
}

let sentence = Sentence(sentence: "Hello world", lang: "en")
let jsonStr = sentence.toJSONString()
print(jsonStr) // prints {"lang":"en","sentence":"Hello world"}

let sentenceFromJSON: Sentence? = instantiate(jsonString: jsonStr)
print(sentenceFromJSON!) // same as original sentence
Reply

#4
**Swift 4** supports the Encodable protocol e.g.

struct Sentence: Encodable {
var sentence: String?
var lang: String?
}

let sentence = Sentence(sentence: "Hello world", lang: "en")


Now you can automatically convert your Struct into JSON using a JSONEncoder:

let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(sentence)

Print it out:

let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonString)

{
"sentence": "Hello world",
"lang": "en"
}

[To see links please register here]


Reply

#5
Use the [NSJSONSerialization class](

[To see links please register here]

).

Using this for [reference](

[To see links please register here]

), you may need to create a function which returns the JSON serialized string. In this function you could take the required properties and create a NSDictionary from them and use the class mentioned above.

Something like this:

struct Sentence {
var sentence = ""
var lang = ""

func toJSON() -> String? {
let props = ["Sentence": self.sentence, "lang": lang]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(props,
options: .PrettyPrinted)
return String(data: jsonData, encoding: NSUTF8StringEncoding)
} catch let error {
print("error converting to json: \(error)")
return nil
}
}

}

Because your struct only has two properties it might be easier to just build the JSON string yourself.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through