let nlp_json_string = "{\"appId\":\"**********\",\"cloud\":true}"
let cmd_json_string = "{\"asr\":\"\",\"id\":\(id),\"name\":\"\(name)\",\"nlp\":\"\(nlp_json_string)\",\"subid\":\(subid)}"
print(cmd_json_string)


日志:

{"asr":"","id":260744,"name":"aaaaaa","nlp":"{"appId":"**********","cloud":true}","subid":123743947}


我想构建这样的JSON,但是这种JSON格式是错误的,我该怎么办,问题是“ nlp”键导致JSON未被格式化。 (注意:“ nlp”值的类型必须为字符串),谢谢!

最佳答案

您可以使用Encodable协议自行选择将对象转换为JSON字符串或JSON对象。
请尝试了解示例

//This the the customer structure
struct Customer: Codable {

    var name: String?
    var id: String?
    var account: Account?
}

//This is customer's account structure
struct Account: Codable {

    var acId: String?
    var openedDate: Date?
}

//Main View Controller.
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //Call this fnctions to initiate the process.
        self.makeJson()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func makeJson() {

        //Make the account object
        let accountInfo = Account.init(acId: "100100234", openedDate: Date())

        //Make the customer object
        let customer = Customer.init(name: "Naresh", id: "dfg-2561", account: accountInfo)

        do {

            //make data object
            let data = try JSONEncoder.init().encode(customer)

            //print as JSON String
            let jsonString = String.init(data: data, encoding: String.Encoding.utf8)
            print(jsonString ?? "Not parsed")

            //print as JSON Object
            let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
            print(jsonObject)

        }
        catch {
            print(error.localizedDescription)
        }
    }
}


看终端。这将同时打印json字符串和json对象。

关于ios - 使用swift创建JSON,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52397743/

10-14 17:52
查看更多