0
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. (note: the type of "nlp" value needs to be a String), thanks!

2
  • write actual JSON which one you wants as output. Commented Sep 19, 2018 at 3:56
  • let nlp_json_string = "{\\\"appId\\\":\\\"RD4724382C28463C824C424808D01A79\\\",\\\"cloud\\\":true}" let cmd_json_string = "{\"asr\":\"\",\"id\":(id),\"name\":\"(name)\",\"nlp\":\"(nlp_json_string)\",\"subid\":(subid)}" Commented Sep 19, 2018 at 4:17

3 Answers 3

1

You can use the Encodable protocol to convert an object to JSON string or JSON object upto your choice. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

The easy way is to create a multiline String:

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

Comments

0

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

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

If you want to insert nlpJsonString as a dictionary remove the double quotes

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.