gpt4 book ai didi

ios - 如何接收 json 字符串并将其转换为字典?

转载 作者:行者123 更新时间:2023-12-01 15:54:30 28 4
gpt4 key购买 nike

我在下面粘贴了一个 JSON

{
"name" :
{
"id" : "name",
"label" : "name field",
"disabled" : false,
"display" : true,
"pattern" : "^\\+(?:[0-9] ?){6,14}[0-9]$",
"type" : "text"
},
"age" :
{
"id" : "age",
"label" : "age",
"disabled" : false,
"display" : true,
"pattern" : "^\\+(?:[0-9] ?){6,14}[0-9]$",
"type" : "text"
}
}

我需要将此 JSON 字符串传递到我的方法中并将其转换为字典类型 Dictionary<String,Dictionary<String,Any>> 的字典

首先我尝试在传递给方法之前验证 JSON 字符串,它总是说无效的 json

let jsonData = json.data(using: String.Encoding.utf8)

if JSONSerialization.isValidJSONObject(jsonData) {
print("Valid Json")
} else {
print("InValid Json")
}

知道为什么这个 JSON 字符串总是返回无效JSON?

我已经在 Playground 上试过了,请查看截图 enter image description here

最佳答案

您正在将数据检查为 isValidJsonObject,这就是它给出无效 json 的原因。您应该尝试将数据转换为 jsonObject,然后检查 isValidJsonObject

我试过如下,它给出了有效的 json

 let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])

let jsonObject = try!JSONSerialization.jsonObject(with: jsonData, options: [])

if JSONSerialization.isValidJSONObject(test) {
print("Valid Json")
} else {
print("InValid Json")
}

关于ios - 如何接收 json 字符串并将其转换为字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63740740/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com