'How to write JSON to Realm in Swift

I can't find information how to write my JSON data to my Realm DB in Swift.

I have class:

class News: Object {
    dynamic var newsID: String = ""
    dynamic var newsTitle: String = ""
    dynamic var newsFullText: String = ""
    dynamic var newsAutor: String = ""
    dynamic var newsCommentCount: String = ""
    dynamic var newsSeenCount: String = ""
    dynamic var newsDate: String = ""
    dynamic var newsCategory: String = ""
}

In here I take JSON from server:

func parseJSONData(data: NSData) -> [News] {

    do {
        let temp: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
        let myNSData = temp.dataUsingEncoding(NSUTF8StringEncoding)!

        let jsonResult = try NSJSONSerialization.JSONObjectWithData(myNSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        let jsonNews = jsonResult["posts"] as! [AnyObject]
        for jsonnewes in jsonNews {
            let newsJson = News()
            newsJson.newsTitle = jsonnewes["post_title"] as! String
            newsJson.newsAutor = jsonnewes["author_name"] as! String
            newsJson.newsFullText = jsonnewes["full_text"] as! String
            newsJson.newsID = jsonnewes["id"] as! String
            newsJson.newsCategory = jsonnewes["menu_category_name"] as! String
            newsJson.newsDate = jsonnewes["create_date"] as! String
            newsJson.newsSeenCount = jsonnewes["review"] as! String
            newsJson.newsCommentCount = jsonnewes["comment_count"] as! String
            newsItems.append(newsJson)
        }
    } catch {
        print(error)
    }
    return newsItems
}

And how to write my data to Realm DB?



Solution 1:[1]

for update filed . you should define method in newsRealm for primary key:

class NewsRealm: Object {
    dynamic var newsID: String = ""
    dynamic var newsTitle: String = ""
    dynamic var newsFullText: String = ""
    dynamic var newsAutor: String = ""
    dynamic var newsCommentCount: String = ""
    dynamic var newsSeenCount: String = ""
    dynamic var newsDate: String = ""
    dynamic var newsCategory: String = ""

      override static func primaryKey() -> String? {
        return "newsID"
      }
}

and then for update :

func insertOrUpdate(news: News) {
    let realm = try! Realm()
    try! realm.write({
        let newsRealm = NewsRealm()
        newsRealm.newsTitle = news.newsTitle
        newsRealm.newsAutor = news.newsAutor
        newsRealm.newsFullText = news.newsFullText
        .
        .
        .
        realm.add(newsRealm, update: true)            })

}

if a new filed so your object add into database but there are in database your object be update .

sorry for my english ;)

Solution 2:[2]

This code works for me, you shouldn't create class News and NewsRealm, just one:

  import SwiftyJSON

    class News: Object {
       @objc dynamic var newsID: String?
       @objc dynamic var newsTitle: String?

     convenience init(value: JSON) {
       self.init()
       for (key, value) in value {
          switch key {
           case "newsID":
              self.newsID = value.stringValue
           case "newsTitle":
              self.newsTitle = value.stringValue
           }
        }
      }
     }

Somwhere in code

    let model = News(value: jsonObject)

Solution 3:[3]

Using Swift 5 and RealmSwift v10.20.0

Try setting a primary key to your News class with this code:

override static func primaryKey() -> String? {
    return "newsID"
}

Then you can parse and save the JSON this way:

do {
    try! realm.write {
        let json = try! JSONSerialization.jsonObject(with: jsonData, options: [])
        realm.create(News.self, value: json, update: .modified)
    }
} catch {
    print("ERROR: \(error.localizedDescription)")
}

Or, if your class doesn't have a primary key, you can code this instead:

    realm.create(News.self, value: json, update: .error)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Farhad Faramarzi
Solution 2 ThomasW
Solution 3