Answers for "convert string any to json swift"

3

swift parse json

let string = #"{"name": "watashi", "number": 42, "pi": 3.141592, "array": [2, 3, 5, 7, 11, 13]}"#

let data = string.data(using: .utf8)!
let object = try! JSONSerialization.jsonObject(with: data, options: [])

let jsonObject = object as! [String: Any]

let nameField   = jsonObject["name"]    as? String
let numberField = jsonObject["number"]  as? Int
let piField     = jsonObject["pi"]      as? Double
let arrayField  = jsonObject["array"]   as? [Any]

print("The name argument is \(nameField)")
print("The number is \(numberField)")
print("The value of pi is \(piField)")
print("the array value is \(arrayField)")
Posted by: Guest on February-12-2020
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 string any to json swift"

Code answers related to "Swift"

Browse Popular Code Answers by Language