Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在Swift 3中生成JSON字符串?_Ios_Json_Swift_Clarifai - Fatal编程技术网

Ios 如何在Swift 3中生成JSON字符串?

Ios 如何在Swift 3中生成JSON字符串?,ios,json,swift,clarifai,Ios,Json,Swift,Clarifai,我正在尝试向需要以下格式的API发送请求: { "inputs": [ { "data": { "image": { "base64": "iVBORw0KGgoAAAIVnFT/DPAAAAAElFTkSuQmCC..." } } } ] } 这是我在Swift 3中尝试的: let base6

我正在尝试向需要以下格式的API发送请求:

{
    "inputs": [
        {
            "data": {
                "image": {
                    "base64": "iVBORw0KGgoAAAIVnFT/DPAAAAAElFTkSuQmCC..."
                }
            }
        }
    ]
}
这是我在Swift 3中尝试的:

let base64 = ["base64": "1010101..."]

let image: [String: Any] = ["image": base64]

let data: [String: Any] = ["data": image]

var input = [Dictionary<String, Any>]()

input = [data]

let jsonData = try! JSONSerialization.data(withJSONObject: input, options: .prettyPrinted)
它产生了如下字符串:

(
        {
        data =         {
            image =             {
                base64 = 1010101;
            };
        };
    }
)
现在,我在自作主张。它是有效的…但它是丑陋的地狱,只是真的站不住脚

let imageAsString = "{\"inputs\": [{\"data\": {\"image\": {\"base64\": \"\(strBase64)\"}}}]}"
我的另一个想法是我可以创建一系列嵌入式对象:一个保存字典的数据对象;保存数据对象的图像对象;以及保存数据对象数组的输入对象

class Image {
    var base64 = Dictionary<String, String>()
}

class Data {
    var image = Image()
}

class Inputs {
    var inputs = [Data]()
}
但是初始化它们并调用JSONSerialization.data不起作用,因为这需要一个dictionary对象

我现在对引入第三方插件并不感兴趣。关于如何使用本机iOS库将这些嵌套对象转换为json有什么想法吗?

绝对有!在Swift 4中使用可编码协议和JSONECODER将实现以下目的:

struct ImageObj: Codable {
    let base64: String
}

struct DataObj: Codable {
    let image: ImageObj
}

struct InputObj: Codable {
    let data: DataObj
}

struct InputsContainerObj: Codable {
    let inputs: [InputObj]
}

let imageObj = ImageObj(base64: "abc123")
let dataObj = DataObj(image: imageObj)
let inputObj = InputObj(data: dataObj)
let inputsContainerObj = InputsContainerObj(inputs: [inputObj])

let encoder = JSONEncoder()
do {
    let jsonData = try encoder.encode(inputsContainerObj)
    let jsonString = String(data: jsonData, encoding: .utf8)!

    print(jsonString) //{"inputs":[{"data":{"image":{"base64":"abc123"}}}]}
} catch _ as NSError {

}
如果Swift 3是您唯一的选择,那么您必须使JSONSerialization.data起作用:


可能是你打印输入而不是jsonData吗?不,但我很感谢你的提问。我编辑了这个问题,只是添加了如何打印JSON数据。您没有打印JSON,而是将它转换为基础对象的结果。尝试printStringdata:jsonData,编码:.utf8!你会发现你的JSON是正确的。我决定这是我升级到Xcode 10和Swift 4的借口。您的Swift 4解决方案运行得非常好。非常感谢。
struct ImageObj: Codable {
    let base64: String
}

struct DataObj: Codable {
    let image: ImageObj
}

struct InputObj: Codable {
    let data: DataObj
}

struct InputsContainerObj: Codable {
    let inputs: [InputObj]
}

let imageObj = ImageObj(base64: "abc123")
let dataObj = DataObj(image: imageObj)
let inputObj = InputObj(data: dataObj)
let inputsContainerObj = InputsContainerObj(inputs: [inputObj])

let encoder = JSONEncoder()
do {
    let jsonData = try encoder.encode(inputsContainerObj)
    let jsonString = String(data: jsonData, encoding: .utf8)!

    print(jsonString) //{"inputs":[{"data":{"image":{"base64":"abc123"}}}]}
} catch _ as NSError {

}
let dict = ["inputs": [["data": ["image": ["base64": "abc123"]]]]]
do {
    let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
    let jsonString = String(data: jsonData, encoding: .utf8)!

    print(jsonString)

    /*
    {
        "inputs" : [
            {
            "data" : {
                "image" : {
                    "base64" : "abc123"
                }
            }
            }
        ]
    }
    */

} catch _ as NSError {

}