Converting JSON ARRAY into NSNumber Arrays - ios

I've retrieved data from a JSON web service and saved it into the following array
_soldamount =
(
0,
0,
0,
0,
"62.69",
"48.3",
81,
"59.83",
"162.57",
0,
"40.67",
)
I believe this array is saved as a string. how can I convert this array into an array of NSnumbers? Thanks for the help!

NSArray *_soldamount = #[ #0, #0, #0, #0, #"62.69", #"48.3", #81, #"59.83", #"162.57", #0, #"40.67"];
NSArray *numbers = [_soldamount valueForKey:#"doubleValue"];
creates an array of NSNumbers. The original array can contain NSNumber
or NSString objects.

You can do it using the following code:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&e];
What is stored in the json variable will depend on the JSON data. It is most commonly either an NSDictionary or NSArray, and it looks like yours would be an NSArray probably.

If these values are intended to be stored as numbers, your web service should be returning them as such. In other words, a value with quotes (") around it is a string regardless of whether or not the string is numerical.
If you do not have control of the web service and still wish to store these values as NSNumbers, you can use [NSNumber numberWithFloat:[string floatValue]] or you may wish to use [string doubleValue] if the strings may contain large values or high precision floating point values.
See Gavin's answer on how to use the NSJSONSerialization class if you aren't using it already.

NSError *error;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray *soldAmount = [json objectForKey:#"amount"]; // Your array of strings.
// Convert string array to number array
NSMutableArray *numberArray = [NSMutableArray array];
[soldAmount enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[numberArray addObject:[NSNumber numberWithFloat:[(NSString *)obj floatValue]]];
}];

use [NSnumber numberWithInteger:[string integerValue]]

Related

Parsing of JSON array returning blank array

I have an array which is of below kind.
{"Hotweeks":[{"Image":"http://www.example.com/wp-content/uploads/0970E01L.jpg","Description":"Ocean Shores, WA","PostTitle":"Windjammer Condominiums"},
{"Image":"","Description":"","PostTitle":"0970O01L"},
{"Image":"","Description":"","PostTitle":"0970I08L"},
{"Image":"","Description":"","PostTitle":"0970I06L"},
{"Image":"","Description":"","PostTitle":"0970I04L"},
{"Image":"","Description":"","PostTitle":"0970i03L"},
{"Image":"","Description":"","PostTitle":"0970I02L"},
{"Image":"","Description":"","PostTitle":"0970I01L"},
{"Image":"","Description":"","PostTitle":"0970E02L"},
{"Image":"","Description":"","PostTitle":"0970E01L"},
{"Image":"http://www.example.com/wp-content/uploads/0936E01L.jpg","Description":"Manson, WA","PostTitle":"Wapato Point"},
{"Image":"","Description":"","PostTitle":"0936O05L"},
{"Image":"","Description":"","PostTitle":"0936O04L"},
{"Image":"","Description":"","PostTitle":"0936O03L"},
{"Image":"","Description":"","PostTitle":"0936O02L"},
{"Image":"","Description":"","PostTitle":"0936O01L"},
{"Image":"","Description":"","PostTitle":"0936I01L"},
{"Image":"","Description":"","PostTitle":"0936E03L"},
{"Image":"","Description":"","PostTitle":"0936E02L"},
{"Image":"","Description":"","PostTitle":"0936E01L"}]}
Which I am trying to parse using the below code.
NSArray *array = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);
This is returning null in Nslog.
…"Description":"Ocean Shores, WA,"PostTitle":…
is missing a " after Ocean Shores, WA. It should be
…"Description":"Ocean Shores, WA","PostTitle":…
Use a JSON validator to check for this type of thing. There are many to pick from. I use the Chrome apps JSON Lint and JSON Editor.
The top level of your Json file is an object, not an array (it doesn't start with '['). That being said, if you check array's type like this: NSLog("%#", [array class] you'll probably see it's a NSDictionary.
To get the array you can do this:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSArray *array = jsonDict[#"Hotweeks"];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);

string handling in ios

I am getting String data from server in the format below. I want to get the value for every tag like phonenumber and name etc. I am able to convert it in array by comma separator. how to get individual values?
Company:Affiliated CO,Organization:TECHNICAL EDUCATION
SOCIETY,Organization:SINHGAD,Organization:National Basketball Association,Person:Parikshit N. Mahalle,PhoneNumber:81 98 22 416 316,PhoneNumber:9120-24100154,Position:Professor,SportsEvent:NBA.
Say your original string is stored in rawString.
You need to :
1) split the string by ,
NSArray *pieces = [rawString componentsSeparatedByString:#","];
2) for each item in this array, split it by :, and add it to a dictionary :
NSMutableDictionary *dict = [NSMutableDictionary new];
for (NSString *piece in pieces) {
NSArray *splitPiece = [piece componentsSeparatedByString:#":"];
// key is at splitPiece[0], value is at splitPiece[1]
dict[splitPiece[0]] = splitPiece[1];
}
Then you'll have a dictionary of what you wanted in the first place.
But as suggested in the comments, it would be far better (and more flexible) for you to receive JSON data.
Edit: your original string shows there are multiple fields named Organization. The code I've given is not designed to handle such cases, it's up to you to build upon it.
If this data is not being returned as a JSON object then you'll have to go with #Clyrille answer. But if it is JSON then NSJSONSerialization:JSONObjectWithData:options:error: will be the way to go.
EXAMPLE
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:/*urlResponse*/ options:0 error:nil];
NSString *company = [json objectForKey:#"Company"];
NSString *Organization = [json objectForKey:#"Organization"];
NSString *Person = [json objectForKey:#"Person"];
NSString *PhoneNumber = [json objectForKey:#"PhoneNumber"];
NSString *Position = [json objectForKey:#"Position"];
NSString *SportsEvent = [json objectForKey:#"SportsEvent"];

iOS enumerate json remove objectkey

I'm struck how to enumerate JSON by remove first object in iOS programming as below
From
[{"001": {"name":"test", "url":"test"},"002":{"name":"test1", "url":"test1"},"003":{"name":"test2", "url":"test2"}}]
to
[ {"name":"test", "url":"test"},{"name":"test1", "url":"test1"},{"name":"test2", "url":"test2"}]
Pls help to recommend me or suggestion coding.
Thank you.
Try this,
NSArray *jsonArray = //parsedJsonArray
NSDictionary *values = [jsonArray objectAtIndex:0];
NSArray *valuesArray = [values allValues];
And the valuesArray will contain the data in format,
[ {"name":"test", "url":"test"},
{"name":"test1", "url":"test1"}, {"name":"test2", "url":"test2"}]
You can easily convert a json string to a NSMutableArray :
NSError *error;
// Get a NSMutableArray from the json string
NSData *data = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *arrayResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
// Remove the first object
[arrayResult removeObject:[arrayResult firstObject]];
jsonDataArray1=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"001"]];
jsonDataArray2=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"002"]];
jsonDataArray3=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"003"]];
jsonDataArrayFinal=[[NSMutableArray alloc]initWithObjects:jsonDataArray1,jsonDataArray2,jsonDataArray3 nil];
initialize all above arrays in viedidload

How to get key/value pair from NSDictionary?

I need little help with NSDictionary. How can I get 1 pair, lets say a value for "id" if I have dictionary
NSDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:NSJSONReadingMutableContainers error:&error];
and it looks like this:
Thanks for Your help.
The shortest way:
NSNumber *number = allCourses[#"semacko"][#"id"];
Try this:
NSDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:NSJSONReadingMutableContainers error:&error];
[allCourses enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
// do something with key and obj
}];
NSDictionary *semacko = [allCourses objectForKey:#"semacko"];
NSNumber *number = [semacko objectForKey:#"id"];
NSNumber *number = allCourses[#"semacko"][#"id"];
or if you want to iterate all objects:
for(NSDictionary* course in allCourses) {
NSNumber *number = course[#"id"];
}
NSString *name =[[NSString alloc]initWithFormat:#"%#",[Dictionaryname objectForKey:#"key"]];
by this code you can access the value that corresponds to the key that specified in the objectforkey keyword
You can try:
NSNumber *courseID = [allCourses valueForKeyPath:#"semacko.id"];
For setting value:
- setValue:forKeyPath:

Understand and use this JSON data in iOS

I created a web service which returns JSON or so I think. The data returned look like this:
{"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}}
To me, that looks like valid JSON.
Using native JSON serializer in iOS5, I take the data and capture it as a NSDictionary.
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
NSLog(#"json count: %i, key: %#, value: %#", [json count], [json allKeys], [json allValues]);
The output of the log is:
json count: 1, key: (
invoice
), value: (
{
amount = "1139.99";
checkoutCompleted = 1;
checkoutStarted = 1;
id = 44;
number = 42;
}
)
So, it looks to me that the JSON data has a NSString key "invoice" and its value is NSArray ({amount = ..., check...})
So, I convert the values to NSArray:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
But, when stepping through, it says that latestInvoice is not a CFArray. if I print out the values inside the array:
for (id data in latestInvoice) {
NSLog(#"data is %#", data);
}
The result is:
data is id
data is checkoutStarted
data is ..
I don't understand why it only return the "id" instead of "id = 44". If I set the JSON data to NSDictionary, I know the key is NSString but what is the value? Is it NSArray or something else?
This is the tutorial that I read:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Edit: From the answer, it seems like the "value" of the NSDictionary *json is another NSDictionary. I assume it was NSArray or NSString which is wrong. In other words, [K,V] for NSDictionary *json = [#"invoice", NSDictionary]
The problem is this:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
In actual fact, it should be:
NSDictionary *latestInvoice = [json objectForKey:#"invoice"];
...because what you have is a dictionary, not an array.
Wow, native JSON parser, didn't even notice it was introduced.
NSArray *latestInvoice = [json objectForKey:#"invoice"];
This is actually a NSDictionary, not a NSArray. Arrays wont have keys. You seem capable from here.
Here I think You have to take to nsdictionary like this
NSData* data = [NSData dataWithContentsOfURL: jsonURL];
NSDictionary *office = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *invoice = [office objectForKey:#"invoice"];

Resources