Json values into NSArray Parsing in IOS - 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);

Related

How to parse a JSON dictionary and put the keys and values in separate arrays - Objective C

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];
}

iOS fetching json object from json string

#"SaveRegistrationIDResult" : #"{\"Table\":[{\"Return_Code\":1,\"Return_Message\":\"ALREADY REGISTERED\"}]}"
I'm finding it impossible to fetch data from this json string.
I'm getting the table Table Object as a NSDictionary using this code.
NSMutableDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSData *processedJsondata = [jsonData objectForKey:#"SaveRegistrationIDResult"];
but I getting errors for everything i try ahead.
I'd like to fetch data from within the Table array ('Return_Code') and print it in a Log.
You are getting json string so you can parse it like,
id jsonString = #"{\"Table\":[{\"Return_Code\":1,\"Return_Message\":\"ALREADY REGISTERED\"}]}"; // or [yourDictionary objectForKey : #"SaveRegistrationIDResult"];
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Now you can get value of any key from above object like,
NSArray *arr = [jsonObject objectForKey : #"Table"];
NSLog(#"your result : %#", arr);
Lion's comment worked.
This is how I fetched the value. Any optimizations welcome.
NSMutableDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *processedJsondata = [jsonData objectForKey:#"SaveRegistrationIDResult"];
NSData *tableData = [processedJsondata dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *tableJsonObject = [NSJSONSerialization JSONObjectWithData:tableData options:0 error:nil];
NSArray *tableArray = [tableJsonObject objectForKey:#"Table"];
NSDictionary *tableObject = [tableArray objectAtIndex:0];
NSString *reposnseCode = [tableObject objectForKey:#"Return_Message"];
NSLog(#"%#",reposnseCode);

How to convert data string to json object and string in iOS?

How to convert string to JSON object or JSON array in iOS?
my JSON string Like That.
{"Data": [{"ID":"1","Name":"Raj"},{"ID":"2","Name":"Rajneesh"}]}
I want to get ID or Name from this string please help me if anyone now this.
Thank You.
I try below code but print null
NSString *JsonString=#"{"Data": [{"ID":"1","Name":"Raj"},{"ID":"2","Name":"Rajneesh"}]}";
NSData *objectData = [JsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:0 error:&error];
NSArray* array = [json objectForKey:#"Data"];
NSLog(#"Print Array %#",array);
Use this
NSString *str=#"{\"Data\": [{\"ID\":\"1\",\"Name\":\"Raj\"},{\"ID\":\"2\",\"Name\":\"Rajneesh\"}]}";
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
NSMutableArray *dataArr=[dict valueForKey:#"Data"];
for (NSDictionary *userData in dataArr) {
NSLog(#"Id:%# Name:%#",[userData valueForKey:#"ID"],[userData valueForKey:#"Name"]);
}
Always Remember that when there are { } curly brackets, it means it is Dictionary and when [ ] this, means Array
NSURL *url=[NSURL URLWithString:#"Your JSON URL"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *array = json[#"Data"];
for(NSMutableDictionary *dic in array)
{
NSLog(#"%#",dic[#"ID"]); // give 1 & 2
NSLog(#"%#",dic[#"Name"]); // Raj and Rajneesh
}
This is not the correct JSON string which can be parsed by Objective c, get string from encoder and you will get a valid string, other then that for JSON to Dictionary conversion is simple in iOS as its natively supported.
NSData *data = [strJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];

How can i parse json data from pushwoosh iphone

How can i parse below data:
u = "{\"userid\":\"Living123\"}";
I need to get Living123 as a string.
You can use this library to convert NSString to NSDictionary.
Import "SBJson.h" in your .m file and use following code
NSDictionary *dictionary = [u JSONValue];
NSString *userId = [dictionary valueForKey:#"userid"];
Edit
Alternatively you can use NSJSONSerialization to convert NSString to NSDictionary
NSError *e = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:u options:NSJSONReadingMutableContainers error:&e];

Conversion from object to json text ios

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\"}]"}

Resources