Create JSON in swift
One problem is that this code is not of type Dictionary
.
let jsonObject: [Any] = [
[
"type_id": singleStructDataOfCar.typeID,
"model_id": singleStructDataOfCar.modelID,
"transfer": savedDataTransfer,
"hourly": savedDataHourly,
"custom": savedDataReis,
"device_type":"iOS"
]
]
The above is an Array
of AnyObject
with a Dictionary
of type [String: AnyObject]
inside of it.
Try something like this to match the JSON you provided above:
let savedData = ["Something": 1]
let jsonObject: [String: Any] = [
"type_id": 1,
"model_id": 1,
"transfer": [
"startDate": "10/04/2015 12:45",
"endDate": "10/04/2015 16:00"
],
"custom": savedData
]
let valid = JSONSerialization.isValidJSONObject(jsonObject) // true
how to create json object in swift 5
Not sure about JSON but according to giving JSON and code part.
JSON should be {"orderItems" : [{"product_id" : 19 , "quantity" : 2 , "size_key" : "39 40 42"}],"retailer_id":20,"status":"initial"}
JSON creator code:
var para : [String:Any] = [String:Any]()
var prodArray : [[String:Any]] = [[String:Any]]()
para["retailer_id"] = 20
para["initial"] = "status"
for product in colorsArray {
var prod : [String : Any] = [String : Any]()
if let productId = product.product?["id"] {
prod["product_id"] = productId
}
prod["quantity"] = "1"
prod["size_key"] = variabledata
prodArray.append(prod)
}
para["orderItems"] = prodArray
print(para)
Create JSON object with Swift Xcode
You've got the structure of your data hierarchy wrong converting from JSON to swift.
It should be...
struct Order: Codable {
let household: Household
}
struct Household: Codable {
let personDetails: [Person]
}
struct Person: Codable {
let age: Int
let maritalStatus: String
let minimumEmploymentOverExtendedPeriod: Bool
let workStatus: String
let pregnant: Bool
let attendingSchool: Bool
let disabled: Bool
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let order = try! decoder.decode(Order.self, from: Data(testJson.utf8))
returns
Person(age: 18, maritalStatus: "single",
minimumEmploymentOverExtendedPeriod: false, workStatus: "recent_loss",
pregnant: false, attendingSchool: false, disabled: false)]
Also worth pointing out is the use of the .keyDecodingStrategy
to ease the converting from snake case. This saves defining the CodingKeys
. Obviously this will only work where you're happy to keep the naming the same.
Create JSON array and JSON Object in swift
Create a new prodArray
array which holds all the prod
dictionary(name and quantity.) Set this prodArray for para
array corresponding to products
key.
Issue in your code:- In your forin loop, you are over-riding the value corresponding to "products"
key.
let para:NSMutableDictionary = NSMutableDictionary()
let prodArray:NSMutableArray = NSMutableArray()
para.setValue(String(receivedString), forKey: "room")
para.setValue(observationString, forKey: "observation")
para.setValue(stringDate, forKey: "date")
for product in products
{
let prod: NSMutableDictionary = NSMutableDictionary()
prod.setValue(product.name, forKey: "name")
prod.setValue(product.quantity, forKey: "quantity")
prodArray.addObject(prod)
}
para.setObject(prodArray, forKey: "products")
How to create JSON from a dictionary in Swift 4?
After trying out various ways, the below way is what worked for me for getting the exact format required by the backend.
var messageDictionary = [
"sender":"system1@example.com",
"recipients":[
"system2@example.com"
],
"data":[
"text" : data
]
] as [String : Any]
let jsonData = try! JSONSerialization.data(withJSONObject: messageDictionary)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)
How to generate JSON string in Swift 3?
Absolutely! Using the Codable
protocol and JSONEncoder
in Swift 4 will do the trick:
struct ImageObj: Codable {
let base64: String
}
struct DataObj: Codable {
let image: ImageObj
}
struct InputObj: Codable {
let data: DataObj
}
struct InputsContainerObj: Codable {
let inputs: [InputObj]
}
let imageObj = ImageObj(base64: "abc123")
let dataObj = DataObj(image: imageObj)
let inputObj = InputObj(data: dataObj)
let inputsContainerObj = InputsContainerObj(inputs: [inputObj])
let encoder = JSONEncoder()
do {
let jsonData = try encoder.encode(inputsContainerObj)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString) //{"inputs":[{"data":{"image":{"base64":"abc123"}}}]}
} catch _ as NSError {
}
If Swift 3 is your only option, then you will have to make JSONSerialization.data
work:
let dict = ["inputs": [["data": ["image": ["base64": "abc123"]]]]]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString)
/*
{
"inputs" : [
{
"data" : {
"image" : {
"base64" : "abc123"
}
}
}
]
}
*/
} catch _ as NSError {
}
How can I create JSON string from model data Swift?
The following decodes the json example and create new AppointmentDownloadModel objects which are then encoded to Data (and converted to a string)
var models = [AppointmentDownloadModel]()
let decoder = JSONDecoder()
do {
let response = try decoder.decode(ResponseData.self, from: data)
if let appointments = response.appointments {
models = appointments.map { AppointmentDownloadModel(appointmentModel: $0)}
}
} catch {
print(error)
}
let encoder = JSONEncoder()
do {
let modelData = try encoder.encode(models)
let jsonString = String(data: modelData, encoding: .utf8)
print(jsonString)
} catch {
print(error)
}
Swift 5 : Create JSON with Codable / Struct from my variables
As you have full controll over your structure and there is no collection involved i would recommend to put everything in one struct instead of scattering it over many different:
struct UserProfile: Codable{
var id: String
var name: String
var lastname: String
var street: String
var country: String
}
Regarding caching. As you can mark this struct Codable
it can be easily stored in Userdefaults
as Data
. This extension on Userdefaults
should allow you to access UserProfile
in a typesafe manner.
extension UserDefaults{
var userProfile: UserProfile?{
get{
guard let data = data(forKey: "userProfile") else{
return nil
}
return try? JSONDecoder().decode(UserProfile.self, from: data)
}
set{
set(try? JSONEncoder().encode(newValue), forKey: "userProfile")
}
}
}
Usage example:
//Write
UserDefaults.standard.userProfile = UserProfile(id: UUID().uuidString, name: "First", lastname: "Last", street: "nowhere", country: "atlantis")
//Read
let profile = UserDefaults.standard.userProfile
Edit:
Editing example:
As this is a struct it gets copied every time something changes.
So read the value in a var. Modify it and save it to the defaultStore.
var profile = UserDefaults.standard.userProfile
profile?.country = "newCountry"
UserDefaults.standard.userProfile = profile
Related Topics
Why Are Doubles Printed Differently in Dictionaries
Convert Swift Array to Dictionary With Indexes
How to Convert Hex Number to Bin in Swift
What Is the Real Benefit of Using Raycast in Arkit and Realitykit
Swift - How to Mutate a Struct Object When Iterating Over It
Swift - Custom Setter on Property
Default Value For Optional Generic Parameter in Swift Function
Command Compileswiftsources Failed With a Nonzero Exit Code Xcode 10
Why Is the Shorthand Argument Name $0 Returning a Tuple of All Parameters
In Swift 3, How to Calculate the Factorial When the Result Becomes Too High
Multiple Workers in Swift Command Line Tool
Swift: Failing to Copy Files to a Newly Created Folder
Swift3 Optionals Chaining in If Conditions Bug
Retrieve Only 5 Users At a Time :Firebase [Like Instagram]
Swift: Setting an Optional Property of a Protocol
Projecting the Arkit Face Tracking 3D Mesh to 2D Image Coordinates