objc How do I get the string object from this Json array? - ios

This is part of an incoming array:
variantArray: (
(
{
CardinalDirection = "North-West";
DirectionVariantId = "DcCi_1445_171_0_0";
Distance = "2.516606318971459";
RouteName = "Woodsy";
Shape = {
Points = (
{
I want to get the value of DirectionVariantId
I would normally loop and use
NSMutableArray *myString = [variantArray[i] valueForKey:#"DirectionVariantId"];
This isn't working and results in an exception when I try to examine the last character in the string:
NSString *lastChar = [myString substringFromIndex:[myString length] - 1];
This is a new data set for me and I'm missing something..
Thanks for any tips.

Json contain two curly bracket means nested array.
Try:
NSString *myString=[[[variantArray objectAtIndex:0] objectAtIndex:0] objectForKey:#"DirectionVariantId"];

I think you're looking for [variantArray[i] objectForKey:#"DirectionVariantId"];
You'd need to convert the object within your incoming array (variantArray[i]) to a NSDictionary but it might already be judging by your original output.

Related

Parse the data from JSON

I just worried to parse the JSON data as below format. Here I need to parse userId as string or integer.
(
{
Response = success;
UserId = 214;
}
)
In my previous workout data is fetching like this ( 214 ).
If its coming like (214), why don't you try doing substring on it. Performing substring will remove the starting and ending braces. Try something like this.
NSString *badStr = #"(214)";
NSString *goodStr = [badStr substringFromIndex:1];
NSString *finalStr = [goodStr substringToIndex:[goodStr length]-1];
This will help you get the exact 214 value without the braces.
Hope this helps.

Want to save all the valueForKey in dictionary in either 1 array or dictionary

for (NSDictionary *fbDictionary in self.latestReactionsArray) {
LatestReaction *latestReaction = [[LatestReaction alloc]init];
NSDictionary *subFBDictionary = [fbDictionary objectForKey:#"participant"];
NSString *facebookUserID = [subFBDictionary valueForKey:#"facebook_id"];
NSNumber* reactionIDNum = [fbDictionary valueForKey:#"reaction_id"];
int reactionID = [reactionIDNum intValue];
NSLog(#"what is name%# and %# and %d",facebookUserID, self.latestReactionsArray,reactionID);
}
I want to save all [fbDictionary valueForKey:#"reaction_id"] in an array or dictionary. How do I do this? Thanks.
Try this:
NSArray *reactionIDs = [self.latestReactionsArray valueForKey:#"reaction_id"];
That will give you an array of reaction IDs.
The reflection in Objective C is not powerful enough to get a usable list of properties that you want to map. Instead, you should implement a class method that returns a list of properties you want to map to JSON and use that.
Lastly, a common "Gotcha" is trying to add nil to a dictionary. You'll need to do a conversion from nil to [NSNull null] and back for the conversion to work properly.

How to get rid of multiple sets of parentheses in an array

I'm using RESTKit to do some object mapping for a JSON and I'm mapping an array. The JSON that I'm mapping looks like this: "parameters":[{"parameter_value":["Smith"]}, {"parameter_value":[66211]}]
The array that I'm getting looks like this:
Parameter Value: (
(
Smith
),
(
66211
)
)
When I try to convert the array to a string via this code: NSString *nameidvalue = [[parameterValueArray valueForKey:#"description"] componentsJoinedByString:#""]; The string nameidvalue turns into this:
(
Smith
)(
66211
)
How exactly do I get rid of the parentheses so what I'm left with is Smith, 66211
You asked about eliminating "sets of parentheses", but given that the underlying structure is a series of nested collections (dictionaries and arrays), you can achieve the desired effect by effectively collapsing a level or two from that structure. You can do this with the KVC collection operator, #unionOfArrays, used in conjunction with valueForKeyPath. If you really want to do a string manipulation, we can do that, but it seems more logical to write code that renders a simple array, and then you can use componentsJoinedByString if you really want a simple string at the end.
What makes this answer a little complicated is that the reported JSON doesn't match the NSLog of the resulting NSDictionary, so I'm unclear as to precisely what the input was. So I'm going to show two permutations of this KVC collection operator, one that matches the provided sample JSON, and another that matches the JSON that I inferred from the NSDictionary structure you reported.
If the JSON is:
{"parameters":[{"parameter_value":["Smith"]}, {"parameter_value":[66211]}]}
You could then parse that as follows (I'm using the NSJSONReadingMutableContainers so that I can change the results; if you're not trying to change the array, but rather just extract the appropriate results, then you don't need to make it mutable; it's up to you):
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
That would yield a NSMutableDictionary structure would be:
{
parameters = (
{
"parameter_value" = (
Smith
);
},
{
"parameter_value" = (
66211
);
}
);
}
But you could replace parameters with:
dictionary[#"parameters"] = [dictionary[#"parameters"] valueForKeyPath:#"#unionOfArrays.parameter_value"];
Yielding:
{
parameters = (
Smith,
66211
);
}
But, if you had JSON like:
{"parameters":[["Smith"],[66211]]}
And if you parsed that with the same NSJSONSerialization as above, that would yield a dictionary like:
{
parameters = (
(
Smith
),
(
66211
)
);
}
And you could replace the parameters value using the KVC collection operator #unionOfArrays again, this time using self:
dictionary[#"parameters"] = [dictionary[#"parameters"] valueForKeyPath:#"#unionOfArrays.self"];
That would yield:
{
parameters = (
Smith,
66211
);
}
You asked:
How exactly do I get rid of the parentheses so what I'm left with is Smith, 66211
If you, literally, just want #"Smith, 66211", you could then just take this simplified array and now use componentsJoinedByString:
NSString *string = [dictionary[#"parameters"] componentsJoinedByString:#", "];
Try
NSString *nameidvalue = [[parameterValueArray valueForKey:#"parameters"] componentsJoinedByString:#""];
Replace with,
NSString *nameidvalue = [[parameterValueArray valueForKey:#"description"] componentsJoinedByString:#","];
Try like.. Access the Objectforkey of Parameter Value and store into a dicitonary and then access the objectforkey of Smith and store the value into a string.
NSError *e = nil;
NSMutableArray *JSON = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
NSDictionary *value = [JSON objectforkey:#"parameter_value"];
You will get the expected values.

Accessing NSDictionary retrieves an object instead of NSString

I have an NSDictionary that I fill with JSON. It all looks great, and it is partially working for me. I am setting a property of my class that is of type NSString equal to a value for a certain key, which oddly enough sets my property equal to an object with the object being the string value I need.
The dictionary (printed description):
miscInfo:
<__NSArrayI 0x7494ab0>(
{
Abbreviation = DR;
DateInactive = "";
Description = Drowsiness;
ForQueue = 2430;
IsAdditive = 0;
IsReserved = 1;
MiscCodeTypeStr = AVR;
PluralDescription = "";
ReservedDescription = Drowsiness;
}
I am setting it on my property like so:
self.ReactionName = [miscInfo valueForKeyPath:#"Description"];
Which produces:
I've tried casting it as NSString such as:
self.ReactionName = (NSString*)[allergenAdverseReaction valueForKeyPath:#"Description"];
but nothing gives. What am I doing wrong?
miscInfo is an array containing a dictionary, so
self.ReactionName = [[miscInfo objectAtIndex:0] objectForKey:#"Description"];
would give the result that you expect. Or, using the modern array and dictionary
subscripting syntax:
self.ReactionName = miscInfo[0][#"Description"];
Remark: In your code
self.ReactionName = [miscInfo valueForKeyPath:#"Description"];
valueForKeyPath is applied to each element of the array, and an array with all
the values is returned. That is what you see in the Xcode debugger window.
This "feature" can be very useful, but in general (as Hot Licks commented above)
objectForKey is the right method to get a value from a dictionary. And
self.ReactionName = [miscInfo objectForKey:#"Description"];
throws a descriptive runtime exception if miscInfo is not a dictionary as expected.
It looks to me like miscInfo is an array of dictionaries. In that case valueForKey will return an array. See if the code below works. If it does, then it is an array of dictionaries.
self.ReactionName = [[allergenAdverseReaction valueForKeyPath:#"Description"]lastObject];

ios assigning value to a string from an array

So I have a basic array:
NSMutableArray *answerButtonsArrayWithURL = [NSMutableArray arrayWithObjects:self.playView.coverURL1, self.playView.coverURL2, self.playView.coverURL3, self.playView.coverURL4, nil];
The objects inside are strings. I want to access a random object from that array
int rndValueForURLS = arc4random() % 3;
and assigning it a value. I've tried manny different approaches but my recent one is
[[answerButtonsArrayWithURL objectAtIndex:rndValueForURLS] stringByAppendingString:[self.coverFromRightAnswer objectAtIndex:self.rndValueForQuestions]];
Any help will be much appreciated. Thanks
You need to assign it. You're already building the new value like that:
NSString *oldValue = answerButtonsArrayWithURL[rndValueForURLS];
NSString *newValue = [oldValue stringByAppendingString:[self.coverFromRightAnswer objectAtIndex:self.rndValueForQuestions]];
The part you're missing :
answerButtonsArrayWithURL[rndValueForURLS] = newValue;
Above would be the way to replace the immutable string with another. If the strings are mutable, that is, they were created as NSMutableString, you could do:
NSMutableString *value = answerButtonsArrayWithURL[rndValueForURLS];
[value appendString:[self.coverFromRightAnswer objectAtIndex:self.rndValueForQuestions]];
Note:
Everywhere I replace the notation :
[answerButtonsArrayWithURL objectAtIndex:rndValueForURLS];
with the new equivalent and IMO more readable:
answerButtonsArrayWithURL[rndValueForURLS];

Resources