简体   繁体   English

iOS从JSON API编码字符串

[英]iOS Encode String From JSON API

I am downloading data from an API in JSON using NSURLConnection and NSJSONSerialization . 我正在使用NSURLConnectionNSJSONSerialization从JSON中的API下载数据。 The JSON is returning all & as in the HTML ampersand literal: & JSON返回所有&如HTML和号文字: & .

I'm wondering if that's supposed to be encoded properly on the server, with UTF-8 to Unicode, and received by me as & or if I'm supposed to be doing that work. 我想知道是否应该在服务器上使用UTF-8将其正确编码为Unicode,并以&接收到,或者是否应该这样做。

Here is the code I use to download the data: 这是我用来下载数据的代码:

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:api_url]];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
                               NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
                               // do work
                           }];

I do not believe there is a requirement in the JSON spec for it to be one way or the other. 我认为JSON规范中没有要求它是一种方法。 When I am personally working with an API that I have control over, I like that sort of work to be done on the server side (better yet, I prefer to keep view stuff like HTML markup out of the data in the first place). 当我亲自使用自己可以控制的API ,我喜欢在服务器端完成这类工作(更好的是,我更喜欢将诸如HTML标记之类的视图内容放在数据的首位)。

JSON must be encoded in some Unicode format. JSON必须以某种Unicode格式编码。 The format can be UTF-8, UTF-16 big-endian or little-endian, or UTF-32 big-endian or little-endian. 格式可以是UTF-8,UTF-16大端或小端,或UTF-32大端或小端。 Characters in JSON strings can be encoded like \ for example, but if there are any & characters then that is the data that the server wants to send you. JSON字符串中的字符可以像\\ u007f这样进行编码,但是,如果有&字符,那么这就是服务器要发送给您的数据。 For example, a server could send a string containing html or a URL, and you would receiver that string with & characters and all. 例如,服务器可以发送包含html或URL的字符串,而您将接收带有&字符和全部的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM