ios


How get the value from NSDictionary with JSON


So I have this json
data: {
Thresh: {
id: 412,
key: "Thresh",
name: "Thresh",
title: "the Chain Warden"
},
Aatrox: {
id: 266,
key: "Aatrox",
name: "Aatrox",
title: "the Darkin Blade"
},
Tryndamere: {
id: 23,
key: "Tryndamere",
name: "Tryndamere",
title: "the Barbarian King"
}
I'm trying to get all "id", but the only way I can find is using
[myArray addObject:[dictionary valueForKeyPath:#"data.Aatrox.id"]];
I want to know if have a easy way to get all id's, like without need to put the name example "Aatrox", just "id" or "title".
Here the code that I use to get the json
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:#"myurl"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
Assuming your JSON looks like:
{
"data": {
"Thresh": {
"id": 412,
"key": "Thresh",
"name": "Thresh",
"title": "the Chain Warden"
},
"Aatrox": {
"id": 266,
"key": "Aatrox",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Tryndamere": {
"id": 23,
"key": "Tryndamere",
"name": "Tryndamere",
"title": "the Barbarian King"
}
}
}
If that's the case, then you can then grab the dictionary associated with the key of data, and then grab an array of all the values in that dictionary (i.e. an array of those child dictionaries):
NSArray *values = [dictionary[#"data"] allValues];
And then grab the array of values associated with the id key in each of those dictionaries:
NSArray *ids = [values valueForKeyPath:#"id"];
You can use NSString class - (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator method to separate your JSON object to pieces of strings. After that you can use a for loop to get elements that you need.(This is such a nasty way, but accomplishes what you asked) However, I strongly recommend you to read JSON string as an object by using Jastor like library and by creating your own objects. Maybe this way seems to be hard, but it will be safer than your implementation.
Lets just say your JSON looks like this:
{
"Thresh": {
"id": 412,
"key": "Thresh",
"name": "Thresh",
"title": "the Chain Warden"
},
"Aatrox": {
"id": 266,
"key": "Aatrox",
"name": "Aatrox",
"title": "the Darkin Blade"
},
"Tryndamere": {
"id": 23,
"key": "Tryndamere",
"name": "Tryndamere",
"title": "the Barbarian King"
}
}
and you parse it using
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
You can use KVC collection operations to get exactly what you want. First we need to convert your dictionary to an array of values. Since you don't care about the keys this is easy:
NSArray *values = [dictionary allValues];
Now we want all the IDs so we need to use #distinctUnionOfObjects to get that:
NSArray *ids = [values valueForKeyPath:#"#distinctUnionOfObjects.id"];
We can combine this into a single line if we want:
NSArray *ids = [dictionary valueForKeyPath:#"allValues.#distinctUnionOfObjects.id"];
You can read more about KVC collection operations here: http://nshipster.com/kvc-collection-operators/
I would also suggest using a higher level JSON parsing library such as RestKit.

Related Links

Multiple subviews not showing in loop Swift 3 on ScrollView
iMessage Application is Missing its Required iMessage App Extension - Can Not Run on Device
ios Extension size
Button with image ,image disappear for only ios10
How to add alphabetic sections in TableView from database using swift 3
Is it possible to convert a video to alpha channel video in ios on run time?
Date format for 2016-10-20T13:01:47.317
Xcode8 submission error - how to find out what exactly requires specific permissions on iOS10
Changing UILabel's text only works inside viewDidLoad()
Google Place API Fetch List of Restaurants with food type
Crashlytics doesn't catch Out Of Memory
Watch OS3.1 - Watch app show circular indicator & stuck while tap on push notification
I write a tableView in my view class , but it can't show the dataSource
How to delete userdefault data in rows in a section in Swift?
Cloud Kit Predicate
How to close MFMailComposeViewController?

Categories

HOME
serial-port
saml
amazon-kinesis
twitter-digits
windows-server-2012-r2
whitespace
regression
eps
h2o
wso2-das
bluej
aac
zend-expressive
resolve
googletest
aar
prerender
lazy-loading
flow
api-design
ssrs-2008
curve-fitting
cayley
pcap
background-subtraction
php-carbon
parallax
mediacodec
ocean
silverlight-5.0
json-c
groove
fipy
draggable
vtable
vue2
sagepay
ibm-wcm
logicblox
mergesort
codeigniter-hmvc
backwards-compatibility
oracle-aq
log4perl
zuul
uifont
federation
domdocument
dump
mspgcc
masm32
a-star
jvm-arguments
ifc
jeditorpane
android-sdk-tools
tfs2008
mit-scheme
aplpy
document-ready
post-processor
monkeyrunner
android-gpuimageview
devenv
genexus-gam
sql-server-ce-3.5
esx
typesafe-activator
prettyfaces
django-postgresql
dataformat
ituneslibrary
keymapping
resolver
prudentia
programmers-notepad
xhtml-transitional
xcode4.2
mainwindow
sparc
nsmanagedobjectmodel
python-dateutil
dynamic-usercontrols
quilt
jscience
ruby-1.9.2
katta
gemstone
bubble-popup
mkmapviewdelegate
automapping
excel-web-query
webshop
drupal-gmap
gumstix
coords
code-statistics
fogbugz-on-demand

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App