如何在Swift中正确编码JSON?

时间:2016-05-18 17:43:49

标签: ios json swift

我正在尝试创建一个JSON对象以返回swift中的服务,但我似乎无法找出正确的编码方式。这是我尝试创建JSON对象的当前代码:

        let jsonObject = [
        "entries" : [
            { "old" : {
                "preferenceOptions" : [
                { "preferenceCategoryCode" : {
                "code":"01",
                    "desc":"Paperless Settings"
                },
                                        "preferenceSubCategoryCode":{
                                           "code":"01",
                                           "desc":"Paperless Settings"
                                        },
                                        "preferenceOptionDescription":{
                                           "text":"Explanation of benefits (EOB)",
                                           "languageCode":"EN"
                                        }
                }

                ]
                }

            }
        ]
    ]

我收到错误"一行上的连续陈述必须用';' "从"条目"开始

感谢您提前协助。

1 个答案:

答案 0 :(得分:1)

您的jsonObject正在尝试使用原始JSON语法(使用字典的大括号)而不是Swift语法(其中字典文字使用方括号)。它应该是:

let jsonObject = [
    "entries" : [
        [ "old" : [
            "preferenceOptions" : [
                [ "preferenceCategoryCode" : [
                    "code":"01",
                    "desc":"Paperless Settings"
                    ],
                    "preferenceSubCategoryCode":[
                        "code":"01",
                        "desc":"Paperless Settings"
                    ],
                    "preferenceOptionDescription":[
                        "text":"Explanation of benefits (EOB)",
                        "languageCode":"EN"
                    ]
                ]
            ]
            ]
        ]
    ]
]