I have this code Json format:
{
"weather": [{
"description": "clear sky",
"icon": "01n"
}],
"base": "stations",
"main": {
"temp": 285.514
},
"clouds": {
"all": 0
},
"dt": 1485792967,
"id": 1907296
}
And I want to retrive icon string (01n)
And use this code:
@property(nonatomic,strong) NSString *cityImageName;
self.cityImageName = [[dataJson valueForKey:@"weather"] valueForKey:@"icon"];
And later when I check the variable print:
<__NSSingleObjectArrayI 0x604000009890>(
01n
)
Finally how can I get the string directly? not like a __NSSingleObjectArrayI
You got caught in the Key-Value Coding Trap.
valueForKey
has a special behavior. Applied to an array it returns always an array of all values for the given key.
Never use valueForKey
unless you intend to use KVC. The recommended syntax is objectForKey
or – preferable – key subscription and in case of the array index subscription.
In this case you want to get the value for key icon
of the first item in the array for key weather
.
self.cityImageName = dataJson[@"weather"][0][@"icon"];
However I would add a check if the array is not empty to avoid an out-of-range exception
NSArray *weather = dataJson[@"weather"];
if (weather && weather.count > 0) {
self.cityImageName = weather[0][@"icon"];
}