How to append a float value as float in dictionary? - ios

I need to calculate a MD5 values with a json value to the server like,
{
"name":"swift",
"version":1.0,
"edition":1,
"date":"2014-12-26"
}
In this json the version needs to be send as float 1.0 not 1 and edition as integer 1.
So, I have tried to create a dictionary and done a NSJSONSerialization as,
NSDictionary *d = #{#"name":#"swift",
#"version":[NSDecimalNumber decimalNumberWithString:#"1.0"],
#"edition":[NSNumber numberWithInt:1],#"date":#"2014-12-26"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];
But this is creating a json response as
{
"name":"swift",
"version":1,
"edition":1,
"date":"2014-12-26"
}
So the MD5 value is mismatching.
Can anyone help me with this to create a json with float value for "version" with decimal point (1.0) ?

There is nothing wrong with sending the numeric value 1.0 as simply 1 in JSON. Though you might have a little luck getting the .0 if you encoded a floating point in an NSNumber, vs using an NSDecimalNumber.
`... #"version":#(1.0)...`
The full dictionary:
NSDictionary *d = #{#"name":#"swift",
#"version":#(1.0),
#"edition":#(1),
#"date":#"2014-12-26"};

Create the NSMutableDictionary, convert the number to an NSNumber and put it into the NSMutableDictionary.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
float value = 1.0;
NSNumber *number = [NSNumber numberForFloat:value];
[dict setObject:number forKey:#"version"];
or using literals replace the above two lines with:
dict[#"version"] = #(value);

Related

How to get the value for key #int from NSDictionary?

I am Creating a NSDictionary and adding a key value pair as below
NSDictionary* dictionary = #{ #0: #"I am the value" };
and retrieving the value as below
NSString* value = [dictionary valueForKey:#0];
Application crashed for doing this, I don't understand the reason, I am giving the same data type and value.
What is the datatype of #0, I guess it is NSNumber, If not correct me.
Yes, it's NSNumber type however the problem is somewhere else.
You should call objectForKey instead of valueForKey which is mainly used for KVO.
NSString *value = [dictionary objectForKey:#0];
or better:
NSString *value = dictionary[#0];
valueForKey: is not the proper method for what you are trying to achieve.
you should use:
NSString* value = [dictionary objectForKey:#0];
ValueForKey is for key value coding and expect a NSString as parameters

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

Converting JSON ARRAY into NSNumber Arrays

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

SBJson displays null

I am trying to parse some json data with SBJson to show the current temperature. The example code from this tutorial works perfect: Tutorial: Fetch and parse JSON
When I change the code to my json feed i get a null. I am kind of new to JSON but followed every tutorial and documentation I found. The json source i used: JSON Source
My code with sbjson:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
NSArray* currentw = [(NSDictionary*)[responseString JSONValue] objectForKey:#"current_weather"];
//choose a random loan
NSDictionary* weathernow = [currentw objectAtIndex:0];
//fetch the data
NSNumber* tempc = [weathernow objectForKey:#"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:#"weatherCode"];
NSLog(#"%# %#", tempc, weatherCode);
and of course I have already implemented the other sbjson code.
There is no current_weather key in the JSON data you posted. The structure is:
{ "data": { "current_condition": [ { ..., "temp_C": "7", ... } ], ... } }
Here's a visual representation:
Therefore, to get to temp_C, you'd need to first obtain the top-level data property:
NSDictionary* json = (NSDictionary*)[responseString JSONValue];
NSDictionary* data = [json objectForKey:#"data"];
then, from that, obtain the current_location property:
NSArray* current_condition = [data objectForKey:#"current_condition"];
and finally, from the current_location array, get the element you're interested in:
NSDictionary* weathernow = [current_condition objectAtIndex:0];
Also note that temp_C and weatherCode are strings, not numbers. To transform them to numbers, instead of:
NSNumber* tempc = [weathernow objectForKey:#"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:#"weatherCode"];
you could use something like:
int tempc = [[weathernow objectForKey:#"temp_C"] intValue];
int weatherCode = [[weathernow objectForKey:#"weatherCode"] intValue];
(or floatValue / doubleValue if the value is not supposed to be an int, but rather a float or a double)
You would then use %d (or %f for float / double) as a format string:
NSLog(#"%d %d", tempc, weatherCode);
Provided link returns json without current_weather parameter. There is only current_condition parameter, please review this.
Use NSJSONSerialization instead of JSONValue.
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"jsonDict:%#",jsonDict);
In your link, there is no current_weather key.
NSString* tempc = [[[[jsonDict objectForKey:#"data"] objectForKey:#"current_condition"] objectAtIndex:0] objectForKey:#"temp_C"];

SBJSON Float in NSDictionary written to NSString incorrect

I'm using SBJSON in a project and I'm trying to build a json string from a dictionary.
Here's what's going on, I'm putting floats as NSNumbers into a dictionary:
NSDictionary* tempdic = [[NSDictionary alloc] init];
tempdic = [NSDictionary dictionaryWithObjectsAndKeys:productId, #"productId", [NSNumber numberWithFloat:quantity], #"aantal", price, #"price" , nil];
[orders addObject:tempdic];
NSDictionary* json = [NSDictionary dictionaryWithObjectsAndKeys: orders, #"order", message, #"message", [NSNumber numberWithFloat:orderprice], #"totalPrice",dueDate,#"dueDate", nil];
And then to finally write it as a json string, I tried these three.
1)
NSData* jsonData = [writer dataWithObject:json];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
2)
NSString* jsonString = [json JSONRepresentation];
3)
NSString* jsonString = [writer stringWithObject:json];
Each of these changes 0.95 into 0.95000000000000034355 or even worse 0.949999999999999992344 or something alike.
Why is this happening? How can I prevent this?
Thanks
That's the basic problem with float values. You can't store values which can't be represented by the sum of the power of 2. Thus resulting with the approximate value to your floating point.
e.g. 1.25 can be easily represented as sum of power of 2
i.e. 1*2^0 +1*2^-2 but if you are going to represent 1.33 as sum of power of 2 then the resultant would be 1*2^0 + 1*2^-2 + 1*2^-4 + 1*2^-8 + 1*2^-9 ....
Just read Representable numbers, conversion and rounding on wiki.
And you can check your floating point representation using online tool.
This is the classic problem with floating point numbers. You can, however, use NSDecimalNumber rather than NSNumber to get higher precision (at the cost of lower range of numbers).

Resources