I am new to json.
I want to know that how can I get code and name of country from
http://country.io/names.json
and display it in label.
I only want to know objectForKEy and valueForKey for this.
I want output like,
I want Output like,
IN India
In my tableView
I have two label in my cell, one for Code and another for name.
do like
NSMutableArray *Name = [[NSMutableArray alloc] init];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://country.io/names.json"]];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
for (NSString *findkey in [json allKeys]) {
//[Name addObject:[json objectForKey:findkey]];
[Name addObject:[NSString stringWithFormat:#"%# %#",findkey,[json objectForKey:findkey]]];
}
NSLog(#"Name==%#",Name);
you get output like
Related
I'm trying to parse www.fixer.io JSON to get currency data. I've been having trouble parsing the JSON and trying to separate the keys and values from the "rates" dictionary. I need them separate so I can put them in arrays to display the currency name (ex: USD, EUR, JPN) and their respective rates.
I've read that I have to use the "allKeys" and "allValues" to do this but so far I'm having no luck. Any ideas?
NSURL *fixerURL = [NSURL URLWithString:#"http://api.fixer.io/latest?base=USD"];
NSData *data = [NSData dataWithContentsOfURL:fixerURL];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *arr = [[NSMutableArray alloc]init];
NSMutableArray *arr2 = [[NSMutableArray alloc]init];
NSArray *names;
NSArray *rates;
for (names in json) {
names = [json allKeys];
for (rates in json) {
rates = [json allValues];
}
[arr addObject:names];
[arr2 addObject:rates];
}
self.currencyList = arr;
self.currencyRates = arr2;
[self updateTableView];
Here is the JSON ---> http://api.fixer.io/latest?base=USD
Hope this will help you,
NSURL *fixerURL = [NSURL URLWithString:#"http://api.fixer.io/latest?base=USD"];
NSData *data1 = [NSData dataWithContentsOfURL:fixerURL];
NSError *error;
NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&error];
NSLog(#"%#",json1);
NSDictionary *json = [[NSDictionary alloc]initWithDictionary:[json1 objectForKey:#"rates"]];
NSMutableArray *arr = [[NSMutableArray alloc] initWithArray:[json allKeys]];
NSMutableArray *arr2 = [[NSMutableArray alloc]initWithArray:[json allValues]];
NSLog(#"%#",arr);
NSLog(#"%#",arr2);
as the rates key contains a dictionary not an array so we can’t get country name and currency as dictionary format
if you want to get the country name and currency in different array so you need to get them separately like bellow
NSArray *arrKeys = [[json valueForKey:#"rates"] allKeys];
NSArray *arrValues = [[json valueForKey:#"rates"] allValues];
Based on your JSON response you have to get yoiur all currency rate as below
NSMutableArray *allCurrencyKey = [[json valuesForKey:#"rates"] allKeys];
NSMutableArray *allRates = [json valueForKey:#"rates"];
for(NSString *strCurKey in allCurrencyKey)
{
NSLog (#" %# rate is %# ", strCurKey, [allRates valueForKey :strCurKey ]);
}
Hope this will helps you.
I'm not sure what error you're getting, but when I try to run this code I get data coming back as nil. Which of course crashes the app.
It probably has something to do with the method you are using to fetch the JSON.
dataWithContentsOfURL: should not be used for network-based URLs.
dataWithContentsOfURL:
To fetch data over the network, take a look at NSURLSession.
Use below code to get Rates Nad Currency Names
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
By this response you can get all rates:
NSMutableDictionary *rates = [json objectForKey:#"rates"];
//Get All Currency Names by `allKeys`.
NSArray *currencyTitles = [rates allKeys];
for(NSString *currencyName in currencyTitles){
//Get Value.
NSString *aStrCurValue = [rates objectForKey:currencyName];
}
I'm trying to parse this JSON :
[
{
"text" : "Test",
"color" : "yellow",
},
{
"text" : "Test2",
"color" : "blue",
},
]
I am trying to get two arrays, one with the key "text" and another with the key "color".
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:#"notes"
ofType:#"json"];
NSError *e = nil;
NSData *data = [[NSData alloc] initWithContentsOfFile:jsonPath];
NSArray *parsed = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&e];
if (! [parsed isKindOfClass:[NSArray class]]) {
NSLog(#"Error");
}
NSArray *texts = [[NSMutableArray alloc] init];
NSArray *colors = [[NSMutableArray alloc] init];
for (NSDictionary* dict in parsed)
{
[texts addObject:dict [#"text"]];
[colors addObject:dict [#"color"]];
}
I have an error with the following code:
[texts addObject:dict [#"text"]];
[colors addObject:dict [#"color"]];
How should I fix this?
Looking at your JSON data, you've got an array that contains 2 dictionaries. Each dictionary has keys for text and color.
You can use a trick on the array to get all the values in one:
First, your code to extract the JSON into an NSArray:
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:#"notes"
ofType:#"json"];
NSError *e = nil;
NSData *data = [[NSData alloc] initWithContentsOfFile:jsonPath];
NSArray *parsed = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&e];
Now the trick:
NSArray *textEntries = [parsed valueForKey: #"text"];
NSArray *colorEntries = [parsed valueForKey: #"color"];
EDIT:
The trick is in sending the valueForKey message to an array. When you do that, it passes on the message to every object in the array. The array then builds a new array with the answer it gets back from each object it contains and returns the resulting array to you. This does a whole lot of work for you with a very simple statement.
I'm using a web service that gives back JSON data of jobs. I have called the service and displayed ALL the JSON data as such:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = #"http://jobs.github.com/positions.json?description=python&location=new+york";
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSString *item = [json objectAtIndex:0];
NSLog(#"%#", item);
// Do any additional setup after loading the view.
}
So this returns one job with TON of information such as "description", "company name", "location". I want to be able to get JUST location or JUST description. How would I go about doing that?
All help is appreciated, thanks.
you get an array of dictionaries... replace
NSString *item = [json objectAtIndex:0]; //old
with
for(NSDictionary *item in jsonArray) {
NSLog(#"Item desc : %#", item[#"description"]);
}
In your case you can access it directly:
NSDictionary *item = [json objectAtIndex:0];
NSString *location = [item objectForKey:#"location"];
NSLog(#"%#", location);
Reading the following article will give you a good grounding on parsing JSON data.
http://www.intertech.com/Blog/basic-json-parsing-in-ios/
How to store this data in NSArray?
I'm getting JSON response in this format like this:
{
1 = USA;
4 = India;
}
I need to convert this into NSArray
If your JSON is a string, get an NSData object first:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
Then turn it into an NSDictionary using the NSJSONSerialization class:
NSError* error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
Since you said you want an NSArray, do the following:
NSArray *jsonArray = [jsonDict allValues];
Note that the order of the entries in the array is undefined, according to Apple's documentation. So if you need a particular order, you'll have to figure out a better approach.
This is JSON dictionary, First you convert this to NSDictionary from JSON.
NSDictionary *dictionary = //parse json using NSJSONSerilization
NSArray *array = [dictionary allValues];
allValues will return an array with all objects.
Try this:
NSString *jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dictionary =[jsonString JSONValue];
NSArray *array = [dictionary allValues];
NSLog(#"Array values = %#",array);
What i need
"sampleId":"[{\"TextVal\":\"10233\"}]"
Where i have
NSDictionary *sampledict=#{#"TextVal": #"10233"};
NSArray *arr=[NSArray arrayWithObject:sampledict];
[dict setObject:arr forKey:#"sampleId"];
But converting this to json text gives me
"sampleId":[{TextVal:10233}]
is there a way to get the value as {\"TextVal\":\"10233\"}?
This is for a web service call with POST data with following content.And the web service gives me Bad request error when excluding this \ .hence the requirement
Please note i am using AFNetworking for the purpose of network data fetch
That looks like "nested JSON". You have to create JSON data for the array
arr first, and put that into the outer dictionary. Then create JSON data for the complete
object:
NSDictionary *sampledict = #{#"TextVal": #"10233"};
NSArray *arr = [NSArray arrayWithObject:sampledict];
NSData *innerJson = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];
NSString *innerJsonString = [[NSString alloc] initWithData:innerJson encoding:NSUTF8StringEncoding];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:innerJsonString forKey:#"sampleId"];
NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
Output:
{"sampleId":"[{\"TextVal\":\"10233\"}]"}