ios - JSON 解析错误 Swift 3

标签 ios json swift swift3

我有一些不明白的错误.. 好吧,我发送这个代码

JSONARRAY {
 JSON,
 JSONARRAY,
 JSONARRAY
}

Y 有这个但没有工作或解析不正确,无论两个数组是否添加任何东西

buscarEmpresa=[

"{\n  \"criterio\" : \"fru\",\n  \"tipo\" : \"0\",\n  \"idempresa\" : \"82\"\n}",
  [

  ],
  [

  ]
]

无法读取数据,因为它的格式不正确。

试试这段代码..

let usuario = UsuarioSQL.getUsuario()!
var jArray: [AnyObject] = []

let jUsuario = NSMutableDictionary()
jUsuario.setValue((phBuscar.text?.trimmingCharacters(in: .whitespacesAndNewlines))!, forKey: "criterio")
jUsuario.setValue(String(describing: usuario.tipo_negocio), forKey: "tipo")
jUsuario.setValue(String(describing: usuario.id_server), forKey: "idempresa")
let jData = try! JSONSerialization.data(withJSONObject: jUsuario, options: .prettyPrinted)
let jStr = NSString(data: jData, encoding: String.Encoding.utf8.rawValue) as! String
jArray.append(jStr as AnyObject)

let jaEmpresarial = NSMutableArray()
for i in receive_empresarial {
            let jEmpresarial = NSMutableDictionary()
            jEmpresarial.setValue(i, forKey: "empresarial")
            jaEmpresarial.add(jEmpresarial)
}
jArray.append(jaEmpresarial)

let jaPais = NSMutableArray()
for i in receive_paises {
      let jPais = NSMutableDictionary()
      jPais.setValue(i, forKey: "pais")
      jaPais.add(jPais)
 }
 jArray.append(jaPais)


 let post = try! JSONSerialization.data(withJSONObject: jArray, options: .prettyPrinted)
 let jPost = NSString(data: post, encoding: String.Encoding.utf8.rawValue) as! String

 let sesion = URLSession.shared
 let parameters = "buscarEmpresa=\(jPost)"
 print(parameters)

最佳答案

生成的数据不是有效的 JSON。这可能就是您收到错误的原因。您可以使用 JSON 验证器验证这一点,如果您愿意,但取决于您希望如何设置,您可能需要这行 JSON:

{\n  \"criterio\" : \"some criteria\",\n  \"tipo\" : \"Type\",\n  \"idempresa\" : \"ID\"\n}

在您的 JSON 对象中表示为键值对,或表示为键的值。像这样的东西是有效的:

{
    "criterio": "some criteria",
    "tipo": "Type",
    "idempresa": "ID",
    "empresarial": [{
        "empresarial": 1
    }, {
        "empresarial": 2
    }, {
        "empresarial": 3
    }, {
        "empresarial": 4
    }],
    "pais": [{
        "pais": 10
    }, {
        "pais": 20
    }, {
        "pais": 30
    }]
}

您可以使用这个 JSON validator , 以验证您自己的 JSON。

关于ios - JSON 解析错误 Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42964415/

相关文章:

ios - 游戏结束时插播

javascript - 使用 Reactjs 未定义 componentDidMount 内的变量

javascript - Google 脚本 API 路由错误 409

ios - 在 Swift 中将对象设置为空 NSDictionary

ios - 修复警告 : Attempt to present ViewController on NavigationController whose view is not in the window hierarchy

ios - 如何在 iOS 中裁剪到信箱

ios - 如何编写一个将字符串和泛型类型作为参数的函数?

ios - AVFoundation 相机预览层与水平方向不匹配(Swift 4)

Swift 消息文本区

ios - 等待多个 Alamofire 请求完成