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/