从CoreData解析JSON对象的问题

时间:2018-02-08 10:16:01

标签: ios json swift core-data

我将JSON对象转换为字符串并将其存储到CoreData。但是如何解析单个元素并在检索到我无法弄清楚的JSON对象后获取每个元素....

这就是我获取json对象的方式:

let mobileNumber = mobileNumberTextfield.text
let firstName = firstNameTextField.text

let jsonObject: [String: [String:Any]] = [
    "user1": [
        "mobile_number": mobileNumber,
        "first_Name": firstName,
    ]
]

我打印JSON字符串就是这样......

if let data = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted),
    let str = String(data: data, encoding: .utf8) {
    print(str)
}

打印str给出:

{
  "user1" : {
    "mobile_number" : "567567567",
    "first_Name" : "iopiopi",
  }
}

我将它原样存储到coredata,所以当我将它复原时,我会以与上面相同的格式将其恢复。但是,如何检索单个元素以供以后使用,我无法弄清楚。

如果我拿这样的东西......

for result in  newProductDetails {
    if let prodID = result.value(forKey: "address") as? String {
        print(prodID)

    }
}

并做一个for (key, value) in addDetails.enumerated()&印刷值,它给这个..

 data: {
    address = "{
\n  \"user1\" : {
\n    \"mobile_number\" : \"1236594525\",
\n    \"first_Name\" : \"ghj\"
\n  
}
\n
}";
})

但是如何提取mobile_number&的个别值? first_Name来自它......?

2 个答案:

答案 0 :(得分:3)

将Json字符串转换为字典:

func convertToDictionary(text: String) -> [String: Any]? {

    if let data = text.data(using: .utf8) {

         do {

             return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
          } catch {
             print(error.localizedDescription)
          }
    }
    return nil
}

let str = "{\"name\":\"James\"}"

let dict = convertToDictionary(text: str)

你应该在CoreData中保存这样:

          if let reposArray: AnyObject = json["user1"] as? NSDictionary {

                self.mbleNo = reposArray["mobile_number"] as? String
                let appDelegate = UIApplication.shared.delegate as! AppDelegate
                if #available(iOS 10.0, *) {
                    let managedObjectContext = appDelegate.persistentContainer.viewContext
                    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Fields")
                    let entityDescription = NSEntityDescription.entity(forEntityName: "Fields", in:managedObjectContext)
                    let titleInfo = NSManagedObject(entity: entityDescription!, insertInto: managedObjectContext) as? Fields
                    titleInfo?.setValue(self.mbleNo, forKey: "mobile_number")

                    do {

                        try titleInfo?.managedObjectContext?.save()
                    }
                    catch {
                        print(error)
                    }
                 }
            }

答案 1 :(得分:2)

您正在存储从编码JSON的字符串中获取的数据(NSData)并从CoreData获取相同的数据。这意味着您必须再次解析该NSData实例中的JSON。往返JSON / NSData并返回没什么意义。您可能只想创建一个用户实体,并将手机号码和名字直接存储到CoreData中。