[英]Reading JSON file from dropbox iOS
我有一個場景,應用程序從服務器(保管箱)讀取文件並檢查版本。 如果有新版本可用,請下載該應用程序。
我正在嘗試從鏈接讀取文件,但在 JSON 解析后獲取null
。
NSError *error;
NSString *strFileContent = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://www.dropbox.com/s/22mm417fxdqdn8c/FileStructure.txt?dl=0"]
encoding:NSUTF8StringEncoding
error:&error];
if(!error) { //Handle error
// NSLog(@"strFileContent: %@",strFileContent);
NSData *data = [strFileContent dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"json : %@",[json description]);
}
else
NSLog(@"Error in reading!");
}
DropBox 有什么替代品嗎?
有一種方法,我覺得它很丑,但仍然如此。
第一個問題,正如其他人提到的: yourURLEtcdl=1
。
第二個大問題,該文件是一個 rtf 文件,而不是一個 JSON 對象。
因此,由於有一種方法可以使用 RTF => NSAttributedString => NSString => "JSON" => 獲取您想要的值,因此您可以執行以下操作:
NSError *error;
NSURL *url = [NSURL URLWithString:@"https://www.dropbox.com/s/22mm417fxdqdn8c/FileStructure.txt?dl=1"];
NSString *strFileContent = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
NSLog(@"strFileContent: %@", strFileContent);
if(!error)
{
NSError *rtfError;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[strFileContent dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil
error:&rtfError];
if (rtfError)
{
NSLog(@"RTFError: %@", [rtfError localizedDescription]);
}
else
{
NSLog(@"string: %@", [attributedString string]);
NSData *data = [[attributedString string] dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError)
{
NSLog(@"JSON Error: %@", [jsonError localizedDescription]);
}
else
{
NSLog(@"JSON: %@", jsonDict);
NSInteger version = [[jsonDict objectForKey:@"Version"] integerValue];
NSLog(@"Version: %ld", (long)version);
}
}
}
else
{
NSLog(@"Error: %@", error);
}
正如我所說,我覺得這些不是很好,它有效,但在我看來這個解決方案很混亂(用NSData
傳遞兩次)。
那不是包含 JSON 的文本文件; 它是一個包含 JSON 的 RTF 文件。 這不適用於NSJSONSerialization
:
{\rtf1\ansi\ansicpg1252\cocoartf1347\cocoasubrtf570
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\f0\fs24 \cf0 \{\
"Version": 1.0,\
"ImageList": [\
"Nature.png",\
"Nature-1.png",\
"Ballon.png"\
]\
\}}
您已使用使用 RTF 的編輯器(默認的 Mac TextEdit
)保存了該文件。 您需要重新保存為純文本。
提供的 URL 也不正確。 如果您只需要文件內容,則必須設置 dl=1(url 的最后一個組件)。 像這樣——
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.