Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解码包含数组的JSON字符串_Json_Swift_Macos_Decode_Encode - Fatal编程技术网

解码包含数组的JSON字符串

解码包含数组的JSON字符串,json,swift,macos,decode,encode,Json,Swift,Macos,Decode,Encode,我在下面的类中使用JSONSerialization对JSON字符串进行编码和解码。我可以对NSDictionary和NSArray进行编码,我可以对使用NSDictionary编码的字符串进行解码,但不能对从数组编码的字符串进行解码,这会在JSONSerialization.jsonObject(。。。 在必要的时候,我可以不用阵列工作,但如果能知道为什么会发生这种情况,那就太好了 let a = [1,2,3,4,5] let s = JSON.Encode( a )! JSON.Dec

我在下面的类中使用JSONSerialization对JSON字符串进行编码和解码。我可以对NSDictionary和NSArray进行编码,我可以对使用NSDictionary编码的字符串进行解码,但不能对从数组编码的字符串进行解码,这会在JSONSerialization.jsonObject(。。。 在必要的时候,我可以不用阵列工作,但如果能知道为什么会发生这种情况,那就太好了

let a = [1,2,3,4,5]  
let s = JSON.Encode( a )!
JSON.Decode( s ) // fails    

let a = ["a" : 1, "b" : 2, "c" : 3 ]  
let s = JSON.Encode( a )!
JSON.Decode( s ) // works
-


您正在将结果强制转换为字典,因此它无法与其他内容一起使用

一个解决方案是使函数泛型并指定预期的返回类型

我对代码做了一些清理,基本上,如果函数包含抛出API,建议创建一个函数
throw

classjson{
枚举JSONError:错误{case typeMismatch}
静态函数编码(j:Any)抛出->字符串{
let data=try JSONSerialization.data(使用jsonobject:obj)
返回字符串(数据:数据,编码:.utf8)!
}
静态函数解码(s:String)抛出->T{
让数据=数据(s.utf8)
guard let result=尝试JSONSerialization.jsonObject(使用:data)作为其他{
抛出JSONError.typeMismatch
}
返回结果
}
}
设a=[1,2,3,4,5]
做{
让s=试试JSON.encode(a)
让u:[Int]=尝试JSON.decode
打印(u)
}捕获{打印(错误)}
注(一如既往):


在SWIFT中不使用<代码> NSCORCHOR> ,<代码> NSCONS/<代码>和<代码> NSError < /Cl> >代码>完全没有意义。

SWIFT不是Objtovi.C类不必有基类,所以不要继承<代码> NSbObjs<代码>,除非您有充分的理由这样做,不要使用旧的基础类型有本地的Swift等价物,如
NSString
NSDictionary
NSError
。此外,为什么不使用Swift 4中引入的
jsonecoder
Codable
?主要是因为就Swift而言,我还是有点生疏。这是在不久前我很匆忙的时候写的,我现在才写的再次访问以清理混乱。感谢您的输入。
class JSON: NSObject {

   static func Encode( _ obj: Any ) -> String? {

       do {
           let data = try JSONSerialization.data(withJSONObject: obj, options:JSONSerialization.WritingOptions(rawValue: 0) )

           if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
               return string as String
           }
           return nil
       } catch let error as NSError {
           return nil
       }
   }

   static func Decode( _ s: String ) -> (NSDictionary?) {

       let data = s.data(using: String.Encoding.utf8, allowLossyConversion: false)!
       do {
           // fails here to work on anything other than "{ a : b, c : d }"
           // hates any [1,2,3] arrays in the string
           let json = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
           return json
       } catch let error as NSError {
           return nil
       }

   }   

}
class JSON {

    enum JSONError : Error { case typeMismatch }

    static func encode( _ obj: Any ) throws -> String {
        let data = try JSONSerialization.data(withJSONObject: obj)
        return String(data: data, encoding: .utf8)!
    }

    static func decode<T>( _ s: String ) throws -> T {
        let data = Data(s.utf8)
        guard let result = try JSONSerialization.jsonObject(with: data) as? T else {
           throw JSONError.typeMismatch 
        }
        return result
    }
}


let a = [1,2,3,4,5]
do {
    let s = try JSON.encode(a)
    let u : [Int] = try JSON.decode(s)
    print(u)
} catch { print(error) }