diogenes
diogenes

Reputation: 2119

Swift Realm import Json Array Data

I need to install the initial data into my Swift Realm from a Json array file.

The json data is in a file called "FundData.json".

I think I am having an issue reading the Json data because it is in an array.

What would be the best way to approach this initial setup of the database? I usually use SwiftyJSON. I am not a Json or Realm sort of person.

This is the simplified Realm Class:

import Foundation
import RealmSwift

class Fund: Object  {

    @objc dynamic var symbol:String = ""
    @objc dynamic var name:String = ""
    @objc dynamic var type:String = ""
    @objc dynamic var primary:Bool = false

}

Here is some of the Json data:

[
{
    "symbol": "VTSMX",
    "name": "Vanguard Total Stock Market Index Fund",
    "type": "stock",
    "primary": "true"
},
{
    "symbol": "VFIAX",
    "name": "Vanguard 500 Index Fund",
    "type": "stock",
    "primary": "false"
},
{
    "symbol": "VSMAX",
    "name": "Vanguard Small-Cap Index Fund",
    "type": "stock",
    "primary": "false"
},
{
    "symbol": "VWIGX",
    "name": "Vanguard International Growth Fund Investor Shares",
    "type": "stock",
    "primary": "false"
}
]

I was able to use the Realm example of with a string. I somehow need to get the data from the json file.

let data = "{\"symbol\": \"VTSMX\",\"name\": \"Vanguard Total Stock Market Index Fund\",\"type\": \"stock\",\"default\": \"1\" }".data(using: .utf8)!


try! realm.write {
let json = try! JSONSerialization.jsonObject(with: data, options: [])
        realm.create(Fund.self, value: json, update: .modified)
    }

Thank you.

Upvotes: 1

Views: 605

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51892

Change your parsing line to

let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]

and the array variable will contain an array of dictionaries with your data. So you need to loop over the array to create your Fund objects

do {
    if let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
        print(array)
    }
} catch {
    print(error)
}

will print

[["name": "Vanguard Total Stock Market Index Fund", "primary": "true", "type": "stock", "symbol": "VTSMX"], ["symbol": "VFIAX", "name": "Vanguard 500 Index Fund", "type": "stock", "primary": "false"], ["type": "stock", "primary": "false", "symbol": "VSMAX", "name": "Vanguard Small-Cap Index Fund"], ["primary": "false", "symbol": "VWIGX", "name": "Vanguard International Growth Fund Investor Shares", "type": "stock"]]

You could also look into letting your Fund class implementing Codable but I am not sure if it's worth it here.

Upvotes: 1

Related Questions