Writing JSON File Programmatically Swift

Writing JSON file programmatically swift

You can use JSONSerialization class for this purpose. Please see the code snippet below cooked up in Playground

import Foundation

// Dictionary containing data as provided in your question.
var dictonary : [String : Any] = ["question":"If you want to create a custom class which can be displayed on the view, you can subclass UIView.",
"answers":["True", "False"],
"correctIndex":0,
"module":3,
"lesson":0,
"feedback":"Subclassing UIView gives your class the methods and properties of a basic view which can be placed onto the view."
]

if let jsonData = try JSONSerialization.data(withJSONObject: dictonary, options: .init(rawValue: 0)) as? Data
{
// Check if everything went well
print(NSString(data: jsonData, encoding: 1)!)

// Do something cool with the new JSON data
}

If you run this code in Xcode playground, you can see your data printed in JSON format
Once you have the JSON , you can use the networking library of your choice to send the data over to the server.

Swift 5 (Xcode 11 Betas 5 & 6) - How to write to a JSON file?

Let’s assume for a second that you had some random collection (either arrays or dictionaries or some nested combination thereof):

let dictionary: [String: Any] = ["bar": "qux", "baz": 42]

Then you could save it as JSON in the “Application Support” directory like so:

do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("example.json")

try JSONSerialization.data(withJSONObject: dictionary)
.write(to: fileURL)
} catch {
print(error)
}

For rationale why we now use “Application Support” directory rather than the “Documents” folder, see the iOS Storage Best Practices video or refer to the File System Programming Guide. But, regardless, we use those folders, not the Application’s “bundle” folder, which is read only.

And to read that JSON file:

do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("example.json")

let data = try Data(contentsOf: fileURL)
let dictionary = try JSONSerialization.jsonObject(with: data)
print(dictionary)
} catch {
print(error)
}

That having been said, we generally prefer to use strongly typed custom types rather than random dictionaries where the burden falls upon the programmer to make sure there aren’t typos in the key names. Anyway, we make these custom struct or class types conform to Codable:

struct Foo: Codable {
let bar: String
let baz: Int
}

Then we’d use JSONEncoder rather than the older JSONSerialization:

let foo = Foo(bar: "qux", baz: 42)
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("example.json")

try JSONEncoder().encode(foo)
.write(to: fileURL)
} catch {
print(error)
}

And to read that JSON file:

do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("example.json")

let data = try Data(contentsOf: fileURL)
let foo = try JSONDecoder().decode(Foo.self, from: data)
print(foo)
} catch {
print(error)
}

For more information about preparing JSON from custom types, see the Encoding and Decoding Custom Types article or the Using JSON with Custom Types sample code.

How to save an array as a json file in Swift?

I recommend that you use SwiftyJSON framework. Study its documentation and in addition learn how to write strings to files (hint: NSFileHandle)

Something like the code below, but you really need to study both SwiftyJSON and NSFileHandle to learn how to both serialize JSON data to a file and parse JSON data from a file

let levels = ["unlocked", "locked", "locked"]
let json = JSON(levels)
let str = json.description
let data = str.dataUsingEncoding(NSUTF8StringEncoding)!
if let file = NSFileHandle(forWritingAtPath:path) {
file.writeData(data)
}

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

Create JSON data programmatically from API results in Swift

Create Encodable structs that model the JSON:

struct Locations: Encodable {
let locations: [Location]
}

struct Location: Encodable {
let latitude: Double
let longitude: Double
}

let locations = Locations(locations: [
Location(latitude: 10, longitude: 10),
Location(latitude: 40, longitude: 40)
])

do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(locations)
// use `data` as the payload to send to your server
print(String(bytes: data, encoding: .utf8)!)
} catch {
print(error)
}

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)

Swift: write JSON and save to iPhone File locally

Here is a simple project for you to clone or browse the source files
https://github.com/eSpecialized/WriteJsonToFiles

The View Controller contains the example;
https://github.com/eSpecialized/WriteJsonToFiles/blob/master/WriteToFiles/ViewController.swift

Basically you need to do a few steps for writing;

  1. Assemble your objects (Strings etc).
  2. Convert to JSONEncoded Data using the JSONEncoder.
  3. The actual 'Data' Object can write it's binary content to storage.

To read the data;

  1. You need a JSONDecoder.
  2. You need the FileContents in memory using Data(contents:...)
  3. Decode the in-memory data back into the object like it was stored.

A more complicated example of reading and writing JSON to a Web Service API is on Medium here > https://medium.com/better-programming/json-parsing-in-swift-2498099b78f

The concepts are the same, the destination changes from a file in the users document folder to a web service API. I feel that it is adequate to get you started with reading and writing JSON.

The Medium article goes a step further with introducing you to Data Models and reading and writing those Data Model Structs using the Codable protocol.

Enjoy! :)

How to store json file locally for quick access

Yes, you can certainly do this. After you've read the remote JSON, it will be a Data object.1

Build a URL to a path in your app's caches directory and then use the Data method write(to:options:) to write that data into your file.

On read, check to see if the file exists in the caches directory before triggering a network read. Note that you need to be sure that the filenames you use are consistent and unique. (The same filename must always fetch the same unique data.)


1 Note that Mohammad has a good point. There are better ways of persisting your data than saving the raw JSON. Core Data is a pretty complex framework with a steep learning curve, but there are other options as well. You might look at conforming to the Codable protocol, which would let you serialize/deserialize your data objects in a variety of formats including JSON, property lists, and (shudder) XML.

How to read JSON.text file to produce data type in swift?

Its clear from the error that your file is not included in resources path
Error line > if let path = bundle.path(forResource: "JSON", ofType: "txt")

So, The issue is that your file is not included here musicTests > Build Phases > Copy Bundle Resources

Sample Image



Related Topics



Leave a reply



Submit