将json对象添加到数组

时间:2018-02-09 11:31:31

标签: ios json swift core-data

点击提交按钮,我的文本字段中的数据和其他一些数据正在转换为json对象,如此...

    let categoryName = self.categoryTextField.text
    let categoryId = self.categoryID

    let category_json: [String: [String:Any]] = [
        "categoryDetails": [
            "category_name": categoryName,
            "category_id": categoryId
        ]
    ]

    if let data = try? JSONSerialization.data(withJSONObject: category_json, options: .prettyPrinted),
        let str = String(data: data, encoding: .utf8) {
        print(str) // `str` gives the json object 
        self.categoryStrToPass = str
    }

现在将self.categoryStrToPass分配给另一个json对象,然后最终添加到字符串数组中,如此...

    let productID = self.prodID
    let sellingPrice = self.mrpTextField.text
    let categoryJSON = self.categoryStrToPass

    let jsonObject: [String: [String:Any]] = [
        "prodDetails": [
            "product_id": productID,
            "selling_price": sellingPrice,
    “category_json”: categoryJSON

        ]
    ]

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

现在我将jsonStringArray存储到coredata,就像这样......

_product?.setValue(self.jsonStringArray, forKey:
            "productJsonArray") // productJsonArray is an attribute of type Transformable and Custom class type Array<String>

它正在被提取......

 if let jsonObjArr = result.value(forKey: "productJsonArray") as?
                        Array<NSString> {
                    print(jsonObjArr)

                    } 

现在在2个不同的实例上我提交了数据,这意味着在提取时打印jsonObjArr,它应该在一个数组中有2个不同的json对象,如此...

[{
  "prodDetails" : {
    "product_id" : "0",
    "category_json" : "{\n  \"categoryDetails\" : {\n    \"category_id\" : \"0\",\n    \"category_name\" : \"prodCAT\"\n  }\n}",
    "selling_price" : "500",
  }
}

{
  "prodDetails" : {
    "product_id" : "1",
    "category_json" : "{\n  \"categoryDetails\" : {\n    \"category_id\" : \"0\",\n    \"category_name\" : \"CATNEW\"\n  }\n}",
    "selling_price" : "1000",
  }
}]

但相反,打印jsonObjArr正在给出这个...在两个不同的数组中......如此......

[{
  "prodDetails" : {
    "product_id" : "0",
    "category_json" : "{\n  \"categoryDetails\" : {\n    \"category_id\" : \"0\",\n    \"category_name\" : \"prodCAT\"\n  }\n}",
    "selling_price" : "500",
  }
}]

[{
  "prodDetails" : {
    "product_id" : "1",
    "category_json" : "{\n  \"categoryDetails\" : {\n    \"category_id\" : \"0\",\n    \"category_name\" : \"CATNEW\"\n  }\n}",
    "selling_price" : "1000",
  }
}]

如何在一个数组中获得多个json对象??

3 个答案:

答案 0 :(得分:1)

Swift 4.0:

    let firstObj = ["prodDetails": [
                   "product_id": 5,
                   "selling_price": 6,
                   ]]

    let secondObj = ["prodDetails1": [
                    "product_id1": 5,
                    "selling_price1": 6,
                    ]]

    let jsonObject = jsonStringArray.addingObjects(from: [firstObj,secondObj])

    if let data = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted),

        let str = String(data: data, encoding: .utf8) {
        print(str) //prints array of dictionaries
    }

答案 1 :(得分:0)

您可以将[String:Any]类型的对象添加到数组中,如此

let firstCategoryName = "first"
let firstCategoryId = 1

let firstCategory = [
    "category_name": firstCategoryName,
    "category_id": firstCategoryId
] as [String : Any]

let secondCategoryName = "second"
let secondCategoryId = 2

var category_json = [[String:Any]]()

category_json.append(firstCategory)

let secondCategory = [
    "category_name": secondCategoryName,
    "category_id": secondCategoryId
    ] as [String : Any]

category_json.append(secondCategory)

print(category_json)

然后序列化数组

答案 2 :(得分:0)

category_jsonjsonObject属于同一类。

您需要了解的内容:

(NS)String&lt; == String(data:encoding)data(encoding:) ==&gt; (NS)Data

应用于特定字符串/数据:JSON:

JSON字符串化&lt; == String(data:encoding)data(encoding:) ==&gt; JSON数据

Swift Array / Swift(以及其他符合JSON标准)&lt; == (NS)JSONSerialization.jsonObject(withData:, options:)(NS)JSONSerialization.data(withJSONObject:, options:) ==&gt; JSON数据

你不能追加两个JSON Stringified,你需要至少在顶层有一个数组。

所以,让我们用伪代码连接点(根本不确定方法名称是否没有错误)

let currentData = self.jsonStrToPass.data(encoding: .utf8)
let current = JSONSerialization.jsonObject(with:currentData, options:[]) as [String:[String:Any]]

let finalArray : [[String:[String:Any]]]()
finalArray.append(current)
finalArray.append(jsonObject)

let finalData = JSONSerialization.data(withJSONObject:finalArray, options:[])
let finalString = String(data:finalData, encoding:.utf8)

这是逻辑的。我没有做if lettry / catch等。

我认为在您传递的数据之间传递Any(对于Swift数组/字典而不是字符串)可能更好。编辑它们(追加等)而不是String可能更简单。