在我的项目中,我想将Json字符串从服务器转换为数组,但无法转换,但当我硬编码(直接给出特定的Json字符串)时,Json字符串意味着将被转换。请帮我找到问题。。
在这里,我给出了我所尝试的代码。
var params = NSMutableDictionary()
params = [
"inspectionLogId": inspectionLogIdStr
]
let manager = AFHTTPSessionManager()
manager.requestSerializer = AFJSONRequestSerializer()
manager.responseSerializer = AFHTTPResponseSerializer()
manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/plain", "text/html", "application/json"]) as Set<NSObject> as Set<NSObject>! as! Set<String>?
manager.requestSerializer.setValue("", forHTTPHeaderField: "apptoken")
manager.requestSerializer.setValue(strAppToken, forHTTPHeaderField: "token")
let urlString:NSString = NSString(format: "%@%@", ApiConstantFile().baseUrlProperty,ApiConstantFile().getTemplateDataUrl)
print(urlString)
manager.get(urlString as String, parameters: params, progress: nil, success: {
(operation, responseObject) in
self.stopAnimation()
let jsonstring = String(data: responseObject! as! Data, encoding: String.Encoding.utf8)
print("jsonstring is:, \(jsonstring!)")
let data = jsonstring!.data(using: .utf8)!
print(data)
do {
if (try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]) != nil {
let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as! [Dictionary<String,Any>]
print(jsonArray)
} else {
print("bad json")
}
} catch {
print(error)
}
}, failure: {
(operation, error) in
self.stopAnimation()
print(error)
self.alert(message: error.localizedDescription)
})
当我打印json字符串时,表示它们显示为字符串:
"[{\"propertyId\":\"1\",\"inspectionTemplateId\":1118,\"value\":[{\"widgetControllerId\":141,\"value\":\"Flood Summary Name\"},{\"widgetControllerId\":142,\"value\":\"Did the property flood?\"},{\"widgetControllerId\":143,\"value\":\"no\"}]}]"
但当我直接给出字符串时,意味着它将转换为数组。
let jsonstring = "[{\"propertyId\":\"1\",\"inspectionTemplateId\":1118,\"value\":[{\"widgetControllerId\":141,\"value\":\"Flood Summary Name\"},{\"widgetControllerId\":142,\"value\":\"Did the property flood?\"},{\"widgetControllerId\":143,\"value\":\"no\"}]}]"