Swift 3中的JSONSerialization问题

时间:2017-04-17 13:51:20

标签: json swift

我从api hit收到了base64编码的数据。所以我将其转换为字符串并使用扩展方法对其进行解码。 之后再次使用utf8转换为数据。

do{
     let jsonResult = String(data: data, encoding: .utf8)
     let jsonDecryptedString = jsonResult?.fromBase64()
     let jsonData = jsonDecryptedString?.data(using: .utf8)
  }catch let err{
            print(err)
  }

这是我的Json String(jsonDecryptedString)

{
    'error_Code': '0',
    'error_msg' : 'Valid Request', 
    'Report_list' :
    [
       {
           “ReportID" : "LEGAL-01","ReportRdlName" : "Statement of Suit filed Accounts(Pending for Judgement)","ReportType" :           "1","ReportShortNameEnum" : "SF Pending STMT"
       },
       {
           "ReportID" : "LEGAL-02","ReportRdlName" : "Suit Filed Account during the Month","ReportType" : "1","ReportShortNameEnum" :               "SF During Month"}
       }
   ]
}

如何获得" Report_list"从它使用JSONSerialization

在jsonResult我收到了

"eydlcnJvcl9Db2RlJzogJzAnLCdlcnJvcl9tc2cnIDogJ1ZhbGlkIFJlcXVlc3QnLCAnY2FzZV9saXN0JyA6IFt7IkN1c3RvbWVyTmFtZSIgOiAiTVIgQUJISU5BViBTSEFSTUEiLCJjYXNlX2lkIiA6ICIiLCJBZHZJRCIgOiAibml0ZXNoMTIzIiwiU3VpdFR5cGUiIDogIjEiLCJjYXNlX25hbWUiIDogIlN1aXQgLyBBcHBsaWNhdGlvbiIsInNlc3Npb25fSWQiIDogIjQwOTQ5OTg4OSIsIkJyYW5jaENvZGUiIDogIjA0MDgifV19"

在jsonDecryptedString

"{\'error_Code\': \'0\',\'error_msg\' : \'Valid Request\', \'case_list\' : [{\"CustomerName\" : \"MR ABHINAV SHARMA\",\"case_id\" : \"\",\"AdvID\" : \"nitesh123\",\"SuitType\" : \"1\",\"case_name\" : \"Suit / Application\",\"session_Id\" : \"409499889\",\"BranchCode\" : \"0408\"}]}"

错误是

The data couldn’t be read because it isn’t in the correct format.

2 个答案:

答案 0 :(得分:0)

try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any]

答案 1 :(得分:0)

实际上它与Json的问题不在于正确的合成。 我用double替换单引号

let jsonResult = String(data: data, encoding: .utf8)
let jsonDecodedString1 = jsonResult?.fromBase64()
let jsonDecodedString2 = jsonDecodedString1?.replacingOccurrences(of: "'", with:"\"")      

现在它正常运作。

打印case_list

if let data = jsonDecodedString2?.data(using: String.Encoding.utf8) 
{
    let json = JSON(data: data)

    for item in json["case_list"]
    {
        print(item)
    }            
}

这是输出

 ("0", 
 {
    "CustomerName" : "MR ABHINAV SHARMA",
    "SuitType" : "1",
    "AdvID" : "nitesh123",
    "case_name" : "Suit \/ Application",
    "case_id" : "",
    "BranchCode" : "0408",
    "session_Id" : "738007867"
})

以下是正确的Json formate

let json = "{\"error_Code\": \"0\",\"error_msg\" : \"Valid Request\", \"case_list\" : [{\"CustomerName\" : \"MR ABHINAV SHARMA\",\"case_id\" : \"\",\"AdvID\" : \"nitesh123\",\"SuitType\" : \"1\",\"case_name\" : \"Suit / Application\",\"session_Id\" : \"923137599\",\"BranchCode\" : \"0408\"}]}"