简体   繁体   English

使用swift创建JSON

[英]create a JSON using swift

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)

log: 日志:

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

I want to build a JSON like this, but this JSON format is wrong, what should I do,The problem is that the "nlp" key causes the JSON to not be formatted. 我想构建这样的JSON,但是这种JSON格式是错误的,我该怎么办,问题是“ nlp”键导致JSON未被格式化。 (note: the type of "nlp" value needs to be a String), thanks! (注意:“ nlp”值的类型必须为字符串),谢谢!

You can use the Encodable protocol to convert an object to JSON string or JSON object upto your choice. 您可以使用Encodable协议自行选择将对象转换为JSON字符串或JSON对象。 Please try to understand the example 请尝试了解示例

//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)
        }
    }
}

Look at the terminal. 看终端。 This will print the json string & json object both. 这将同时打印json字符串和json对象。

The easy way is to create a multiline String: 简单的方法是创建多行字符串:

let myJSON: String = """
{ 
  "id" : 12,
  "foo": "bar"
}
"""

First of all take advantage of the new literal string syntax to avoid the confusion of the escaped double quotes. 首先,利用新的文字字符串语法来避免转义的双引号引起的混乱。

Second of all please conform to the naming convention that variables are camelCased 第二,请遵守命名约定,即使用驼峰式变量


Assumed variables : 假设变量:

let name = "Foo"
let id = 1
let subid = 2

The strings look much clearer. 字符串看起来更清晰。

let nlpJsonString = """
{"appId":"**********","cloud":true}
"""

let cmdJsonString = """
{"asr":"","id":\(id),"name":"\(name)","nlp":"\(nlpJsonString)","subid":\(subid)}
"""

As you can see (better now) nlpJsonString is inserted as String (note the wrapping double quotes) so the result is 如您所见(现在更好), nlpJsonString作为String插入(注意包装的双引号),因此结果是

{"asr":"","id":1,"name":"Foo","nlp":"{"appId":"**********","cloud":true}","subid":2}

If you want to insert nlpJsonString as a dictionary remove the double quotes 如果要插入nlpJsonString作为字典,请删除双引号

let cmdJsonString = """
{"asr":"","id":\(id),"name":"\(name)","nlp":\(nlpJsonString),"subid":\(subid)}
"""

then you get 然后你得到

{"asr":"","id":1,"name":"Foo","nlp":{"appId":"**********","cloud":true},"subid":2}

An alternative is to create dictionaries and serialize them 另一种方法是创建字典并序列化它们

let name = "Foo"
let id = 1
let subid = 2

let nlpDict : [String:Any] = ["appId":"**********","cloud":true]
let cmdDict : [String:Any] = ["asr":"","id":id,"name":name,"nlp":nlpDict,"subid":subid]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: cmdDict)
    let json = String(data: jsonData, encoding: .utf8)!
    print(json)
} catch { print("something went wrong", error) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM