Add array of json (which contain inner array) in realm using swift

拟墨画扇 提交于 2019-12-11 06:07:08

问题


I have created API which generate JSON, that JSON looks like this

[
  {
    "id": 105,
    "date": "2018-09-06T22:37:57",
    "date_gmt": "2018-09-06T17:07:57",
    "guid": {
      "rendered": "http://wh2.6ae.myftpupload.com/?p=105"
    },
    "modified": "2018-09-06T22:37:57",
    "modified_gmt": "2018-09-06T17:07:57",
    "slug": "video-post-20",
    "status": "publish",
    "type": "post",
    "link": "http://wh2.6ae.myftpupload.com/video-post-20/",
    "title": {
      "rendered": "Video post – 20"
    },
    "content": {
      "rendered": "",
      "protected": false
    },
    "excerpt": {
      "rendered": "",
      "protected": false
    },
    "author": 1,
    "featured_media": 0,
    "comment_status": "open",
    "ping_status": "open",
    "sticky": false,
    "template": "",
    "format": "video",
    "meta": [

    ],
    "categories": [
      5
    ],
    "tags": [

    ],
    "fimg_url": false,
    "acf": {
      "imagesCarousel": false,
      "youtube_video_id": "mwzExNYs12Y",
      "upload_video": false
    },
    "_links": {
      "self": [
        {
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/posts/105"
        }
      ],
      "collection": [
        {
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/posts"
        }
      ],
      "about": [
        {
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/types/post"
        }
      ],
      "author": [
        {
          "embeddable": true,
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/users/1"
        }
      ],
      "replies": [
        {
          "embeddable": true,
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/comments?post=105"
        }
      ],
      "version-history": [
        {
          "count": 1,
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/posts/105/revisions"
        }
      ],
      "predecessor-version": [
        {
          "id": 111,
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/posts/105/revisions/111"
        }
      ],
      "wp:attachment": [
        {
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/media?parent=105"
        }
      ],
      "wp:term": [
        {
          "taxonomy": "category",
          "embeddable": true,
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/categories?post=105"
        },
        {
          "taxonomy": "post_tag",
          "embeddable": true,
          "href": "http://wh2.6ae.myftpupload.com/wp-json/wp/v2/tags?post=105"
        }
      ],
      "curies": [
        {
          "name": "wp",
          "href": "https://api.w.org/{rel}",
          "templated": true
        }
      ]
    }
  }
]

and I created classes for this

  • Post Class

    import Foundation
    import RealmSwift
    
    class Post : Object{
    
    @objc dynamic var id = 0
    @objc dynamic var date = ""
    @objc dynamic var date_gmt = ""
    @objc dynamic var modified = ""
    @objc dynamic var modified_gmt = ""
    @objc dynamic var slug = ""
    @objc dynamic var status = ""
    @objc dynamic var type = ""
    @objc dynamic var link = ""
    @objc dynamic var format = ""
    @objc dynamic var fimg_url : Bool = false
    
    @objc dynamic var title : Rendered? = nil
    @objc dynamic var excerpt : Rendered? = nil
    @objc dynamic var content : Rendered? = nil
    @objc dynamic var acf : Acf? = nil
    
    
    override static func primaryKey() -> String? {
        return "id"
    }
    }
    
  • ImageCarousel

    import Foundation
    import RealmSwift
    
    class ImagesCarousel: Object {
    
    @objc dynamic var ID = 0
    @objc dynamic var id = 0
    @objc dynamic var title = ""
    @objc dynamic var filename = ""
    @objc dynamic var filesize  = 0
    @objc dynamic var url = ""
    @objc dynamic var date = ""
    @objc dynamic var modified = ""
    @objc dynamic var mime_type = ""
    @objc dynamic var type = ""
    @objc dynamic var subtype = ""
    @objc dynamic var width = 0
    @objc dynamic var height = 0
    @objc dynamic var sizes : Sizes? = nil
    
    override static func primaryKey() -> String? {
        return "ID"
    }
    }
    
  • Acf

    import Foundation
    import RealmSwift
    
    class Acf: Object {
    
    private RealmList<ImagesCarousel> imagesCarousel;
    var imagesCarousel = List<ImagesCarousel>()
    @objc dynamic var youtube_video_id = ""
    
    }
    
  • Rendered

    import Foundation
    import RealmSwift
    
    class Rendered: Object {
    
    @objc dynamic var rendered = ""
    
    }
    
  • Size

    import Foundation
    import RealmSwift
    import Realm
    
    class Sizes: Object {
    @objc dynamic var large = "" 
    }
    

And My swift Code

if let allData = response.result.value as? NSArray{
    let realm = try! Realm()
    for selectedData in allData{
        print(selectedData)

        let jsonData = try? JSONSerialization.data(withJSONObject: selectedData, options: [])

        let myString = String(data: jsonData!, encoding: String.Encoding.utf8)
        print(myString)

        // Insert from Data containing JSON
        try! realm.write {

            let json = try! JSONSerialization.jsonObject(with: data!, options: [])
            realm.create(Post.self, value: json, update: true)
            //realm.add(testData.self, value: json, update: true)
        }
    }
}

Which is giving me this type of error

[__NSCFDictionary longLongValue]: unrecognized selector sent to
 instance 0x7fdcc8785820 2016-07-06 10:25:30.090
 mydrawing[9436:2732447] *** Terminating app due to uncaught exception
 'NSInvalidArgumentException', reason: '-[__NSCFDictionary
 longLongValue]: unrecognized selector sent to instance 0x7fdcc8785820'

but if I remove [ and ] from json data then it's working fine

let data = "{\"id\":1088,\"date\":\"2018-09-06T22:37:57\",\"date_gmt\":\"2018-09-06T17:07:57\",\"guid\":{\"rendered\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/?p=105\"},\"modified\":\"2018-09-06T22:37:57\",\"modified_gmt\":\"2018-09-06T17:07:57\",\"slug\":\"video-post-20\",\"status\":\"publish\",\"type\":\"post\",\"link\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/video-post-20\\/\",\"title\":{\"rendered\":\"Video post &#8211; 20\"},\"content\":{\"rendered\":\"\",\"protected\":false},\"excerpt\":{\"rendered\":\"\",\"protected\":false},\"author\":1,\"featured_media\":0,\"comment_status\":\"open\",\"ping_status\":\"open\",\"sticky\":false,\"template\":\"\",\"format\":\"video\",\"meta\":\"m\",\"categories\":5,\"tags\":\"m\",\"fimg_url\":false,\"_links\":{\"self\":{\"href\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/wp-json\\/wp\\/v2\\/posts\\/105\"},\"collection\":{\"href\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/wp-json\\/wp\\/v2\\/posts\"},\"about\":{\"href\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/wp-json\\/wp\\/v2\\/types\\/post\"},\"author\":{\"embeddable\":true,\"href\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/wp-json\\/wp\\/v2\\/users\\/1\"},\"replies\":{\"embeddable\":true,\"href\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/wp-json\\/wp\\/v2\\/comments?post=105\"},\"version-history\":{\"count\":1,\"href\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/wp-json\\/wp\\/v2\\/posts\\/105\\/revisions\"},\"predecessor-version\":{\"id\":111,\"href\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/wp-json\\/wp\\/v2\\/posts\\/105\\/revisions\\/111\"},\"wp:attachment\":{\"href\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/wp-json\\/wp\\/v2\\/media?parent=105\"},\"wp:term\":{\"taxonomy\":\"category\",\"embeddable\":true,\"href\":\"http:\\/\\/wh2.6ae.myftpupload.com\\/wp-json\\/wp\\/v2\\/categories?post=105\"},\"curies\":{\"name\":\"wp\",\"href\":\"https:\\/\\/api.w.org\\/{rel}\",\"templated\":true}}}".data(using: .utf8)

let realm = try! Realm()

// Insert from Data containing JSON
try! realm.write {

let json = try! JSONSerialization.jsonObject(with: data!, options: [])
realm.create(Post.self, value: json, update: true)
}
  • I refer this link

https://realm.io/docs/swift/latest/#json

  • Finally I think I am not able to add array in realm and I did not find any official method to that.

回答1:


You'r code worked just try to replace this line

  try! realm.write {

            let json = try! JSONSerialization.jsonObject(with: data!, options: [])
            realm.create(Post.self, value: json, update: true)
            //realm.add(testData.self, value: json, update: true)
        }

To this

  try! realm.write {

            let json = try! JSONSerialization.jsonObject(with:  jsonData!, options: [])
            realm.create(Post.self, value: json, update: true)
            //realm.add(testData.self, value: json, update: true)
        }

Result



来源:https://stackoverflow.com/questions/52380522/add-array-of-json-which-contain-inner-array-in-realm-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!