ios - 使用 swift 创建 JSON

标签 ios json

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值的类型必须是String),谢谢!

最佳答案

您可以使用 Encodable 协议(protocol)将对象转换为 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/

相关文章:

ios - 如何将属性添加到使用数据模型创建的核心数据类?

ios - 键盘向上移动时如何固定UIView的位置?

ios - 执行 `await` 后的 Swift 任务和等待/异步队列?

json - 崩溃 : Convert dictionary to Json string in Swift 3

json - Postgres JSON 类型的 JPA2/Hibernate Criteria 或 CriteriaQuery

jquery - 为什么我不能立即使用 $.getJSON() 的结果?

json - 通过 Socket 流式传输一系列 JSON 字符串

ios - 禁用自动滚动 UITableView

ios - 如何通过cocoapods从github向项目添加特定文件

java - 收到的 JSON 与使用 Spring Rest 和 Hibernate 发送的 JSON 不同