使用Coredata保存Json字典

时间:2017-09-09 05:42:08

标签: ios core-data swift3

我是Coredata的新手,在我的项目中,我必须从API解析json,我需要使用核心数据保存解析的json字典。我创建了一个名为Json的新实体并添加了String类型的属性,但是当我喜欢它显示错误''属性的不可接受的类型的属性:属性=“信息”;期望的类型= NSString

但是我不能选择属性类型NSString,以下是我用来使用核心数据保存json字典的代码。请为我建议一个解决方案。

let session = URLSession.shared.dataTask(with: jsonRequest) { (data, response, error) in

        if let res = response {

            print(res)
        }

        if let data = data {

            do {

                let json = try JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary

               let NewData = NSEntityDescription.insertNewObject(forEntityName: "Json", into: context)

                NewData.setValue(json.value(forKey:"result")  , forKey:"information")

                do {

                    try context.save()
                    print("SAVED")
                }

                catch {

                    print(error)
                }

            }

            catch {

                print(error)
            }
        }
    }

    session.resume()

我的json数据如下

{

 "result": [


        {
            "category_name": "today"
        },

        {
            "category_name": "TechCrunch",
            "category_image": "1500899368.jpg"
        },

        {
            "category_name": "Science Daily",
            "category_image": "1500899358.jpg"
        },

        {
            "category_name": "ShowerThoughts",
            "category_image": "1500899351.jpg"
        },

        {
            "category_name": "BBC",
            "category_image": "1500899343.png"
        },


        {
            "category_name": "Goal.com",
            "category_image": "1500899336.jpg"
        },
        {
            "category_name": "Today I Learned",
            "category_image": "1500899329.jpg"
        },


        {
            "category_name": "Times Of India",
            "category_image": "1500899321.png"
        },


        {
            "category_name": "MIT Technology Review",
            "category_image": "1500899313.png"
        },


        {
            "category_name": "Business Insider",
            "category_image": "1500458239.jpg"
        },


        {
            "category_name": "coindesk",
            "category_image": "1500544039.jpg",
            "data": [
                {
                    "category_id": "34",
                    "news_id": "215",
                    "news_quote": "",
                    "title": "Bitcoin drama",
                    "image": "2017-07-20/1500544487.jpg",
                    "date": "2017-09-07 04:10:10"
                },


                {
                    "category_id": "34",
                    "news_id": "225",
                    "news_quote": "",
                    "title": "Bitcoin Price Surges",
                    "image": "2017-07-21/1500629251.jpg",
                    "date": "2017-09-07 04:10:10"
                },


                {
                    "category_id": "34",
                    "news_id": "229",
                    "news_quote": null,
                    "title": "Bitcoin Prices Gain",
                    "image": "2017-07-22/1500635952.jpg",
                    "date": "2017-09-07 04:10:10"
                }
            ]
        }
    ],
    "response": {
        "status": "success",
        "status_code": 1,
        "message": "success"
    }
}

1 个答案:

答案 0 :(得分:1)

首先不要在Swift中使用基金会NSArrayNSDictionary

result的值是[String:Any]词典的数组。使用循环创建新记录并将类别名称分配给information属性。

...

do {

    let json = try JSONSerialization.jsonObject(with: data) as! [String:Any]
    if let result = json["result"] as? [[String:Any]] {
        for category in result {
            let newData = NSEntityDescription.insertNewObject(forEntityName: "Json", into: context)
            newData.information = category["category_name"] as! String
            // or if the entity is not a `NSManagedObject` subclass
            // newData.setValue(category["category_name"] as! String, forKey:"information")
        }

        try context.save()
        print("SAVED")
    }
} catch {
    print(error)
}
  • 要将值保存到category_image,您需要在实体中使用第二个属性。
  • 要在密钥data中保存JSON,您需要第二个与第一个实体有关系的实体。

一些注意事项:

  • 变量名称应以小写字母开头。
  • options行中的JSONSerialization参数可以省略。
  • 循环后只保存一次上下文。
  • 仅使用一个do catch块。