【问题标题】:IOS Swift 4 Any to valid json DataIOS Swift 4 Any 到有效的 json 数据
【发布时间】:2018-04-08 22:08:51
【问题描述】:

我正在使用 MicrosoftAzureMobile 框架从 APP 的 nodeJs 后端获取一些数据。我必须解析实际上是 json 到我的 ViewModel 的响应。微软提供了一个名为invokeApi(someparams)的函数。

问题是,完成处理程序是这样构建的

completion: (data: Any?, response: HTTPURLResponse?, error: Error?) in { ... }

当我现在尝试将其转换为 Data 时,它失败了。所以我必须以某种方式弄清楚如何解析json以在JSONDecoder.decode()中使用它

Data 属性的 Json 如下所示:

{
content =     {
    createDatetime = "...";
    expireDatetime = "...";
    expiresIn = 1234;
    refreshToken = "...";
    token = "...";
    valid = 1;
};
destination = "...";
hash = ...;
status = successful;
type = "sometype";
}

编辑 1: 我尝试使用以下代码转换数据,但没有成功:

let json = data as! Dictionary<String, Any>
let convertedData : Data = NSKeyedArchiver.archivedData(withRootObject: json) as Data
print(convertedData as Data)
let tokenServiceResult = try JSONDecoder().decode(TokenServiceResult.self, from: convertedData)

但这给了我以下错误:

dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))

【问题讨论】:

  • Model等于Json,如果你喜欢我也可以贴出来

标签: ios json swift swift3


【解决方案1】:

你可以试试Decodable协议:

do {
   let myStruct = try JSONDecoder().decode(MyStruct.self, from: data)
      // do what you want here with MyStruct
      // ...
} catch let error {
      // catch error and handled it here
}

struct MyStruct: Decodable {

   let content: Content
   let destination: String
   let hash: String
   let status: Bool
   let type: String
}

struct Content: Decodable {

   let createDatetime: String
   let expireDatetime: String
   let expiresIn: Int
   let refreshToken: String
   let token: String
   let valid: Int
}

【讨论】:

  • 我就是这样,我的问题是我没有弄清楚如何转换任何类型的数据?对于 Data 类型,它不能将 Dictionary 表示为 Data 的完成调用的数据属性,这是 JsonDecoder.decode() 所需要的
【解决方案2】:

invokeApi() 函数已经将响应数据解析为Dictionary&lt;String, Any&gt; 类型的对象。所以无需使用JsonDecoder().decode()将其转换为Object。

【讨论】:

    猜你喜欢
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多