I have following json response.. here i displayed only few lines of it.
How can I replace "&" with & and store in an array.
Thanks in advance.
[
{
"cat_id": "1",
"cat_name": "Dining & Nightlife",
"0": {
"subcat_id": "2",
"subcat_name": "Restaurants"
},
"1": {
"subcat_id": "3",
"subcat_name": "Bar & Club"
}
}
]
Your JSON data isn't properly encoded. In addition to the JSON format, all the strings seem to be HTML encoded. This is a double encoding, which is completely unnecessary.
I strongly recommend you fix this at the source, i.e. on the server. Then you have proper JSON data that can be used without problems by many different clients.
If you cannot fix it on the server, then you have to decode each string attribute in the JSON response. Before you do that, you better investigate if only ampersands are affected (unlikely) or other special characters (such as < > ä ô) as well. Then you can add this to your question and we will likely be able to help you.
Update:
I don't quite understand what classes you're using to keep the parsed JSON data in memory. (You mention arrays.) But to fix the double encoded ampersands, use the following code on each string:
str = [str stringByReplacingOccurrencesOfString: #"&" withString: #"&"];
try this
NSString *sting=[[NSString alloc]init];
sting=[[request responseString] stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSDictionary *resDict =[parser objectWithString:sting error:nil];
U have to do in take array. and using for loop u can replace & to & and that string add in array. and make new araay...
Related
I am stuck with utf-8 to NSString. I am getting this data from web service :
{
Description = "漢字仮名交じり文";
Images =
(
{
imageName = "0_25_07_2012_10_32_54_1343212374.jpg";
}
);
Time = "11:00 am";
actId = 290;
actTitle = "漢字仮名交じり文";
}
Now how can i convert 名 (名) this kind of code to NSString?
I'm pretty sure something is wrong with your web service. If the web service response is JSON or XML data, then the JSON or XML parser should have decoded the special characters. Since it did not, the web service mistakenly uses a double decoding of characters outside the ASCII range.
The best solution is to fix it at the source, i.e. in the web service.
If you can't, then use the stringByDecodingHTMLEntities method from this NSString category, e.g.:
NSString* textValue = [response objectForKey: #"Description"];
textValue = [textValue stringByDecodingHTMLEntities];
You will have to run each string property through this method.
The codes that you have here are called numeric character references. They have nothing directly to do with UTF8 in general.
See this question for a summary of answers to your problem
I need to display subscripts and superscripts (only arabic numerals) within a UILabel. The data is taken from an XML file. Here is the snippet of XML file:
<text><![CDATA[Hello World X\u00B2 World Hello]]></text>
Its supposed to display X2 (2 as superscript). When I read the string from the NSXMLParser and display it in the UILabel, it displays it as X\u00B2. Any ideas on how to make it work?
I think you can do something like this, assuming the CDATA contents have been read into an NSString and passed into this function:
-(NSString *)removeUnicodeEscapes:(NSString *)stringWithUnicodeEscapes {
unichar codeValue;
NSMutableString *result = [stringWithUnicodeEscapes mutableCopy];
NSRange unicodeLocation = [result rangeOfString:#"\\u"];
while (unicodeLocation.location != NSNotFound) {
// Get the 4-character hex code
NSRange charCodeRange = NSMakeRange(unicodeLocation.location + 2, 4);
NSString *charCode = [result substringWithRange:charCodeRange];
[[NSScanner scannerWithString:charCode] scanHexInt:&codeValue];
// Convert it to an NSString and replace in original string
NSString *unicodeChar = [NSString stringWithFormat:%C", codeValue];
NSRange replacementRange = NSMakeRange(unicodeLocation.location, 6);
[result replaceCharactersInRange:replacementRange withString:unicodeChar];
unicodeLocation = [result rangeOfString:#"\\u"];
}
return result;
}
I haven't had a chance to try this out, but I think the basic approach would work
\u00B2 is not any sort of XML encoding for characters. Apparently your data source has defined their own encoding scheme (which, frankly, is pretty stupid as XML is capable of encoding these directly, using entities outside of CDATA blocks).
In any case, you'll have to write your own parser that handles \u#### and converts that to the correct character.
I asked the question to my colleague and he gave me a nice and simple workaround. Am describing it here, in case others also get stuck at this.
Firstly goto this link. It has a list of all subscripts and superscripts. For example, in my case, I clicked on "superscript 0". In the following HTML page detailing "superscript 0", goto "Java Data" section and copy the "⁰". You can either place this directly in XML or write a simple regex in obj-c to replace \u00B2 with "⁰". And you will get nice X⁰. Do the same fro anyother superscript or subscript that you might want to display.
I am getting html content as a string in my webservice response which contains " " in it. When I display that data in webview, " " is converted in junk character. Please let me know how to solve it.
You have to read the string as NSUTF8 encoded string and then pass the string to web view using "loadHTML" method mentioned in UIWebView.
Not only that, if you want to display special characters like copy right, double quotes etc or other language characters in the HTML, you have to use UTF8 encoding.
Use the stringByReplacingPercentEscapesUsingEncoding: method of NSString
like :
NSString *decoded = [yourString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Also to remove use
[yourString stringByReplacingOccurrencesOfString:#" " withString:#" "];
stringByReplacingOccurrencesOfString is deprecated from ios 9
let decoded = yourString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
I have one genuine question which I am facing at this point and I am sure someone might be able to help me.
I have a JSON Post which looks like:
{
"CustomerAccount":{
"CustomerUID":"String content",
"UserName":"String content",
"Password":"String content",
"OldPassword":"String content",
"Email":"String content",
"QuestionUID":2147483647,
"QuestionAnswer":"String content",
"EAlerts":true
}
}
Now I have a dictionay which set's value of CustomerUID, UserName, etc.. Now if I want to bind a upper level to bind all that to CustomerAccount and send as my JSONRepresentation, is there any easier way than actually creating a new dictionary and setting a value of key "CustomerAccount" in this example? I am sure there might be a better way of doing that.
Thanks.
Not entirely sure I follow, but is this what you want maybe:
NSDictionary *dictA = <dictionary_with_customeruid_etc>;
NSDictionary *customerAccountDict = [NSDictionary dictionaryWithObjectsAndKeys:dictA, #"CustomerAccount", nil];
But I'm not sure I follow your question entirely so maybe you want something else. Please let us know a bit more about what you're trying to do.
I don't really understand your question but ill give it a try.
You can easily parse the JSON string to a NSDictionary using JSONKit https://github.com/johnezang/JSONKit
JSONKit is a very fast and lightweight library and you can parse the string and get the wanted value like this:
NSDictionary *dict = [jsonString objectFromJSONString];
NSString *value = [dict valueForKey:#"key"];
To actually set a value in your JSON string you should use rangeOfString: .location to get the range if the existing value then replaceOccurenciesOfString:[jsonString substringWithRange:NSMakeRange(loc,len)] withString:VALUE.
When I fetch the source of any web page, no matter the encoding I use, I always end up with &# - characters (such as © or ®) instead of the actual characters themselves. This goes for foreign characters as well (such as åäö in swedish), which I have to parse from "Å" and such).
I'm using
+stringWithContentsOfUrl: encoding: error;
to fetch the source and have tried several different encodings such as NSUTF8StringEncoding and NSASCIIStringEncoding, but nothing seems to affect the end result string.
Any ideas / tips / solution is greatly appreciated! I'd rather not have to implement the entire ASCII table and replace all occurrances of every character... Thanks in advance!
Regards
I'm using
+stringWithContentsOfUrl: encoding: error;
to fetch the source and have tried several different encodings such as NSUTF8StringEncoding and NSASCIIStringEncoding, but nothing seems to affect the end result string.
You're misunderstanding the purpose of that encoding: argument. The method needs to convert bytes into characters somehow; the encoding tells it what sequences of bytes describe which characters. You need to make sure the encoding matches that of the resource data.
The entity references are an SGML/XML thing. SGML and XML are not encodings; they are markup language syntaxes. stringWithContentsOfURL:encoding:error: and its cousins do not attempt to parse sequences of characters (syntax) in any way, which is what they would have to do to convert one sequence of characters (an entity reference) into a different one (the entity, in practice meaning single character, that is referenced).
You can convert the entity references to un-escaped characters using the CFXMLCreateStringByUnescapingEntities function. It takes a CFString, which an NSString is (toll-free bridging), and returns a CFString, which is an NSString.
Are you sure they originally are not in Å form? Try to view the source code in a browser first.
That really, really sucks. I wanted to convert it directly and the above solution isn't really a good one, so I just wrote my own ascii-table converter (static) class. Works as it should have worked natively (though I have to fill in the ascii table myself...)
Ideas for optimization? ("ASCII" is a static NSDictionary)
#implementation InternetHelper
+(NSString *)HTMLSourceFromUrlWithString:(NSString *)str convertASCII:(BOOL)state
{
NSURL *url = [NSURL URLWithString:str];
NSString *source = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
if (state)
source = [InternetHelper ConvertASCIICharactersInString:source];
return source;
}
+(NSString *)ConvertASCIICharactersInString:(NSString *)str
{
NSString *ret = [NSString stringWithString:str];
if (!ASCII)
{
NSString *path = [[NSBundle mainBundle] pathForResource:kASCIICharacterTableFilename ofType:kFileFormat];
ASCII = [[NSDictionary alloc] initWithContentsOfFile:path];
}
for (id key in ASCII)
{
ret = [ret stringByReplacingOccurrencesOfString:key withString:[ASCII objectForKey:key]];
}
return ret;
}
#end