how to create json object in swift 5

swift create json object
how to create json file in swift
swift object to json
swift parse json array of dictionaries
swiftyjson
swift 5 struct to json
swift json array of objects
swift string to json

how can i create this json :

{"orderItems":"[{\"product_id\":19,\"quantity\":2,\"size_key\":\" 39 40 42\"},"retailer_id":20,"status":"initial"}

here is code :--

let para:NSMutableDictionary = NSMutableDictionary()
let prodArray:NSMutableArray = NSMutableArray()
para.setValue(20 , forKey: "retailer_id")
para.setValue("initial", forKey: "status")

for product in colorsArray {
  let prod: NSMutableDictionary = NSMutableDictionary()
  prod.setValue(product.product?["id"] , forKey: "product_id")
  prod.setValue("1", forKey: "quantity")
  prod.setValue(variabledata, forKey: "size_key")
  prodArray.add(prod)
}

para.setValue(20 , forKey: "retailer_id")
para.setValue("initial", forKey: "status")

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 in swift, setValue(value5, forKey: "r") let jsonData: NSData do { jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization. JSON supports a few basic data types including number, String, Boolean, Array, and Objects (an associated array with key and value pairs). For the loan fields, the loan amount is stored as a numeric value in the JSON-formatted data.

How about this version:

// MARK: - DataStructure
struct DataStructure: Codable {
    let orderItems: [OrderItem]
}

// MARK: - OrderItem
struct OrderItem: Codable {
    let productID, quantity: Int
    let sizeKey: String
    let retailerID: Int
    let status: String

    enum CodingKeys: String, CodingKey {
        case productID = "product_id"
        case quantity
        case sizeKey = "size_key"
        case retailerID = "retailer_id"
        case status
    }
}

Create Object from JSON Object in Swift 5, You were just missing Codable implementation with ObjSportsIcon class. struct ObjSportsList : Codable { var id:Int var name:String var� You see that we needed to create two different “model layers”, just as our JSON data has two “layers”. Tip: Especially when it comes to more complex JSON data, you can use a tool such as quicktype , which automatically creates data models out of your JSON, ready for being used in your Swift project.

You want a JSON string inside a JSON string. To accomplish that you have to encode only the array, then add the value to the dictionary and call JSONSerialization a second time.

Referring to your answer replace

para["orderItems"] =   ("\(prodArray)")

let jsonData = try! JSONSerialization.data(withJSONObject: para )
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)

(By the way please never use that horrible NSString syntax in Swift)

with

let jsonData = try! JSONSerialization.data(withJSONObject: prodArray)
let arrayString = String(data: jsonData, encoding: .utf8)!
para["orderItems"] = arrayString
let resultData = try! JSONSerialization.data(withJSONObject: para)
let jsonString = String(data: resultData, encoding: .utf8)!

Working with JSON in Swift - Swift Blog, Get the latest news and helpful tips on the Swift programming language from the Creating Model Objects from Values Extracted from JSON. If any errors occur while parsing the JSON, the constant json will be nil. You can use a great number of JSON initializers to create a JSON object, including working with strings, Data objects, and other values. You can also use the JSON () initializer to construct a JSON object from a dictionary or array.

var para : [String:Any] = [String:Any]()
var prodArray : [[String:Any]] = [[String:Any]]()

para["retailer_id"] = 20
para["status"] = "initial"

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)")

let jsonData = try! JSONSerialization.data(withJSONObject: para )
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)

output I'm getting ===

{"orderItems":[{"product_id":19,"size_key":" 394042394042","quantity":1},{"product_id":23,"quantity":1,"size_key":" 394042394042"}],"retailer_id":20,"status":"initial"}

just need value of orderItems as

"[{"product_id":19,"size_key":" 394042394042","quantity":1},{"product_id":23,"quantity":1,"size_key":" 394042394042"}]"

" " mising

How to create JSON from a dictiona…, in Swift 4? I have a JSON snipped which needs to be added as the body when I open a websocket. jsonObject(with: jsonData, options: []) How to exactly format the JSOn this way so that the websocket can accept it? Swift. Asked 2 years� Sep 12, 2016. Working with JSON in Swift If your app communicates with a web application, information returned from the server is often formatted as JSON.You can use the Foundation framework’s JSONSerialization class to convert JSON into Swift data types like Dictionary, Array, String, Number, and Bool.

4. JSON in Swift. JSONStringify and JSONParse functions, You can import builtin SDK frameworks/modules into Swift. Type the A JSON Object's root element must be an Array or Dictionary. First we create an Array of Type AnyObject, and we populate it with a Dictionary of mixed type values. JSONObjectWithData returns a nil in case of an error. Next Post. 5. Swift version: 5.2 Paul Hudson @twostraws May 28th 2019 Swift’s Codable protocol makes it easy to convert JSON to native Swift structs and classes – just design data types that hold the same keys and values as your JSON, then use JSONDecoder to convert.

All You Need to Know About JSON With Swift, Creating JSON Objects. Usually, mobile developers don't need to instantiate JSON data because most of the time it's provided from server APIs. Along with Swift 4 (Foundation) now it is natively supported in both ways, JSON string to an object - an object to JSON string. Please see Apple's documentation here JSONDecoder() and here JSONEncoder() JSON String to Object

Working with JSON and Codable in Swift 5, We will build an iOS app that utilizes a JSON-based API provided by Kiva. which can automatically convert JSON formatted data to objects. #1. Save a Swift Array as a json file. The following Swift 3 / iOS 10 code shows how to transform an Array instance into json data and save it into a json file located in an iPhone's document directory using FileManager and JSONSerialization:

Comments
  • Perhaps this would help. stackoverflow.com/a/29516706/9462397 . It is a lot like typescript.
  • this does not contain array
  • That's not valid json.
  • That being said, I would use the Codable protocol for this.
  • At least never use NSMutable... collection types in Swift.
  • You should also add the encoding part.
  • how can i use this please elaborate it .
  • i want orderItems values in String " " .