Answers for "convert data to json swift"

0

struct to json convert in swift

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) }
Posted by: Guest on May-19-2021
0

json to swift

//Well use the data from the source website as shown below
//We can seperate this data into some key points:

/*
	id
	firstName
	lastName
	email
	gender
	ipAddress
*/

//We then make a struct with those propeties

struct TestData: Decodable {
  
  var id: String
  var firstName: String
  var lastName: String
  var email: String
  var gender: String
  var ipAddress: String
}

//We use the Decodable protocol so that we can decode the json into TestData
/*
	Another thing to note:
	Since there is an array of this TestData, we can make another struct with a variable consisting of an array of TestData

*/

struct ListOfData: Decodable {
  var listData: [TestData]
}

//(Assuming you already know how to get data from the web)

//Now, we can decode the information gotten from the website into TestData:

let decoder = JSONDecoder() //Creates an instance of the json decoder
let data = decoder.decode(ListOfData.self, data: //Data gotten from the test site)

//The decoder.decode... basically decodes the data into the ListOfData type
//So, if I print:
	print(data[0].id)
//It prints 1, as the first id of the entire data set is a 1
Posted by: Guest on September-11-2021

Code answers related to "convert data to json swift"

Code answers related to "Swift"

Browse Popular Code Answers by Language