我试图解析一个.json文件,但是当我以为我快要结束时,发生了错误:
无法转换类型' __ NSCFBoolean'的值(0x10c8ba3b8)到' NSString' (0x10ccb2b48)。
我已经完成了我的研究,我发现(惊讶)我的.json中有一些布尔值在字符串中乱七八糟......
那我怎么能避免这个呢?在我尝试将它放入字符串之前,我已经查找了一些方法可以给我一个条形的类型["标签"]但我找不到..
以下是.json和我的(太长时间)代码的摘录:
...{
"id": 3906,
"address": "L\u2019Hotel le 123 Sebastopol 23, boulevard S\u00e9bastopol, Paris, 75002, Le Louvre, Paris",
"name": "123 Sebastopol",
"url": "/bar/paris/le-louvre/123-sebastopol",
"image_url": "https://prh-wbb-prod.s3.amazonaws.com/generic_640_480/WBB%20holding%20image3_54abcf7d218d1_55b8d2128eabb.jpg",
"tags": "Hotel, Cocktail, Terrace",
"latitude": 48.867598851356,
"longitude": 2.3533117460327
}, {
"id": 1523,
"address": "73 Rue d\u0027Aboukir, 75002 Paris, France, Le Louvre, Paris",
"name": "Lockwood",
"url": "/bar/paris/le-louvre/lockwood",
"image_url": "https://prh-wbb-prod.s3.amazonaws.com/bar_640_480/lockwood_001_553f5b2c99f4b.jpg",
"tags": false,
"latitude": 48.867716087563,
"longitude": 2.3469846706722
}...
我的代码:
id = (bar["id"] as? Int)!
name = (bar["name"] as? String)!
adress = (bar["address"] as? String)!
url = (bar["url"] as? String)!
image_url = (bar["image_url"] as? String)!
tags = (bar["tags"] as? String)!
latitude = (bar["latitude"] as? Double)!
longitude = (bar["longitude"] as? Double)!
答案 0 :(得分:2)
这是解决方案:
if let test = bar["tags"] as? String {
tags = (bar["tags"] as? String)!
}else{
tags=" "
}
答案 1 :(得分:0)
一旦我决定在Swift3下解析JSON并且没想到结果是Bool,我就遇到了类似的问题。
这是我的代码,希望它能帮助像我这样不喜欢Swift 3的人。
在我的例子中,JSON输出中的条目是
success = 0;
请注意,"" 围绕成功或 0 这样
"success" = "0"
所以这是我用来从JSON输出中获取Bool值的代码
success = 0
注意到没有" "
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if (jsonResult?["success"] as? Bool)!
{
okToLogIn = true
print(okToLogIn)
}
else
{
okToLogIn = false
print(okToLogIn)
}
所以我只是将它保存为Bool并检查是否为真,我的代码现在可以正常工作。
答案 2 :(得分:-1)
您正尝试将gotoNext() {
fetch('http://url/login/', {
credentials: 'same-origin',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'wasalaa',
password: 'a',
})
}).then(function(response) {
//console.log(response.headers.get('Content-Type'))
//console.log(response.headers.get('Date'))
//console.log(response.status)
//console.log(response.statusText)
//console.log('json',response
//console.log(response.headers.get('JSESSIONID'))
return response.json()
}).then(function(json){
console.log('login response',json)
if(json.message_code === "SUCCESS"){
console.log('user logged')
this.props.navigator.push({
id: 'HomeCaseList',
//sceneConfig: Navigator.SceneConfigs.FloatFromBottom,
});
}
}).catch(function(err){
console.log('error', err)
})
}
值 - false - 解析为Bool
的实例。
将您的代码更改为:
String