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.
Related
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.
I've got some trouble to retrieve some text message from my server, especially with the encoding. Messages can be from many languages (so they can have accents, be in japanese,... ) and can include emoji.
I'm retrieving my message with a JSON with some info. Here is some logs example :
(lldb) po dataMessages
<__NSCFArray 0x14ecc7f0>(
{
author = "User 1";
text = "Hier, c'\U00c3\U00a9tait incroyable";
},
{
...
}
)
(lldb) po [[dataMessages objectAtIndex:0] objectForKey:#"text"]
Hier, c'était incroyable
I'm able to get the correct text with :
const char *c = [[[dataMessages objectAtIndex:indexPath.row] objectForKey:#"text"] cStringUsingEncoding:NSWindowsCP1252StringEncoding];
NSString *myMessage = [NSString stringWithCString:c encoding:NSUTF8StringEncoding];
However, if the message contains emoji, cStringUsingEncoding: return a NULL value.
I don't have control on my server, so I can't change their encoding before messages are sent to me.
The problem is determining the encoding correctly. Emoji are not part of NSWindowsCP1252StringEncoding so the conversion just fails.
Moreover, you are passing through an unnecessary stage. Do not make an intermediate C string! Just call NSString's initWithData:encoding:.
In your case, calling NSWindowsCP1252StringEncoding was always a mistake; I'm surprised that this worked for any string. C3A9 is Unicode (UTF8). So just call initWithData:encoding: with the UTF8 encoding (NSUTF8StringEncoding) from the get-go and all will be well.
I want to save special characters/german/swedish character in NSDictionary and have to post this data to server, but the data saved in the dictionary is converted to some other format as in console output. I am trying to save this string as different typecasts but not getting.
As NSDictionary's data type is generic, and while sending to POST its sent as in the modified format, I want to save this data in NSDictionary as it is, so that it can be sent in proper format to server and readable at server-end
My code is
NSString *playerName = #"Lëÿlã Råd Sölvê"; // dummy player name
NSLog(#"playerName: %#",playerName);
NSDictionary *postParameters = #{#"playerName1": playerName,
#"playerName2": [NSString stringWithString:playerName],
#"playerName3": [NSString stringWithUTF8String:[playerName UTF8String]],
#"playerName4": [NSString stringWithCString:[playerName UTF8String] encoding:NSASCIIStringEncoding],
#"playerName5": [[NSString alloc] initWithString:playerName],
#"playerName6": [NSString stringWithFormat:#"%#",playerName]};
NSLog(#"postParameters: %#",postParameters);
and output is
playerName: Lëÿlã Råd Sölvê
postParameters: {
playerName1 = "L\U00eb\U00ffl\U00e3 R\U00e5d S\U00f6lv\U00ea";
playerName2 = "L\U00eb\U00ffl\U00e3 R\U00e5d S\U00f6lv\U00ea";
playerName3 = "L\U00eb\U00ffl\U00e3 R\U00e5d S\U00f6lv\U00ea";
playerName4 = "L\U00c3\U00ab\U00c3\U00bfl\U00c3\U00a3 R\U00c3\U00a5d S\U00c3\U00b6lv\U00c3\U00aa";
playerName5 = "L\U00eb\U00ffl\U00e3 R\U00e5d S\U00f6lv\U00ea";
playerName6 = "L\U00eb\U00ffl\U00e3 R\U00e5d S\U00f6lv\U00ea";
}
How can I achieve this...
There is nothing wrong with your code.
What you are seeing is an artefact of NSLog and the description method - the former invokes the latter to obtain the textual representation of an object for output. For NSString the string is displayed using Unicode. However for NSDictionary contained strings are displayed using Objective-C Unicode character escape sequences, which have the form '\Uxxxx'.
To assure yourself all is OK you can use:
for (NSString *key in postParameters)
NSLog(#"%# -> %#", key, postParameters[key]);
and everything should display fine (except playerName4 where you mess the string up yourself).
I have pretty simple NSString
f.e
<scirpt attribute_1="x" attribute2="x" attribute3="x" ... attributeX="x"/>
I need to find specific parameter, let's say attribute2 and replace it's value,
I know the exact name of parameter f.e attribute2 but I don't know anything about it's value.
I guess it can be easily done by regexp, but I quite newbie on it.
In conclusion: I want to grab
attribute2="xxxx...xxx"
from incoming string
Note: I don't want to use some 3rd party libs to achieve that (it's temporary hack)
Any help is appreciated
I hacked it together with some string operations:
NSDictionary* valuesToReplace = #{#"attribute_1" : #"newValue1"};
NSString* sourceHtml = #"<scirpt attribute_1=\"x\" attribute2=\"x\" attribute3=\"x\" attributeX=\"x\" />";
NSArray* attributes = [sourceHtml componentsSeparatedByString:#" "];
for (NSString* pair in attributes)
{
NSArray* attributeValue = [pair componentsSeparatedByString:#"="];
if([attributeValue count] > 1) //to skip first "script" element
{
NSString* attr = [attributeValue firstObject]; //get attribute name
if([valuesToReplace objectForKey:attr]) //check if should be replaced
{
NSString* newPair = [NSString stringWithFormat:#"%#=\"%#\"", attr, [valuesToReplace objectForKey:attr]]; //create new string for that attribute
sourceHtml = [sourceHtml stringByReplacingOccurrencesOfString:pair withString:newPair]; //replace it in sourceHtml
}
}
}
It's really only when you want to hack it and you know the format :) Shoot a question if you have any.
you can try this.. https://github.com/mwaterfall/MWFeedParser
import "NSString+HTML.h" along with dependencies
And write like this...
simpletxt.text = [YourHTMLString stringByConvertingHTMLToPlainText];
I have following strings. But I need to separate them by this "jsonp1343930692" and assign them NSString again. How could I that? I could able to separate them to NSArray but I don't know how to separate to NSString.
jsonp1343930692("snapshot":[{"timestamp":1349143800,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448}]}]})
jsonp1343930692("snapshot":[{"timestamp":1349144700,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448,"attr":{"ozone_level":57,"exp":"IN","gridpoint":"30.17:-95.5"}},{"label_id":10,"lat":29.036944,"lng":-95.438333}]}]})
The jsonp1343930692 prefix in your string is odd: I don't know where you string come from, but it really seems to be some JSON string with this strange prefix that has no reason to be there. The best shot here is probably to check if it is normal to have this prefix, for example if you get this string from a WebService it is probably the WebService fault to return this odd prefix.
Anyway, if you want to remove the jsonp1343930692 prefix of your string, you have multiple options:
Check that the prefix is existant, and if so, remove the right number of characters from the original string:
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
if ([str hasPrefix:kStringToRemove])
{
// rebuilt a string by only using the substring after the prefix
str = [str substringFromIndex:kStringToRemove.length];
}
Split your string in multiple parts, using the jsonp1343930692 string as a separator
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
NSArray* parts = [str componentsSeparatedByString:kStringToRemove];
str = [parts componentsJoinedByString:#""];
Replace every occurrences of jsonp1343930692 by the empty string.
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
str = [str stringByReplacingOccurrencesOfString:kStringToRemove withString:#""];
So in short you have many possibilities depending on what exactly you want to do :)
Of course, once you have removed your strange jsonp1343930692 prefix, you can deserialize your JSON string to obtain a JSON object (either using some third-party lib like SBJSON or using NSJSONSerializer on iOS5 and later, etc)
Have a look at the NSJSONSerialization class to turn this into a Cocoa collection that you can deal with.