簡體   English   中英

是否可以使用SBJson4解析NSInputStream?

[英]Is it possible to parse an NSInputStream using SBJson4?

我正在嘗試讀取包含由NSString類型和NSMutableArrays組成的聯系信息對象的JSON文件。 當前,我正在使用NSData讀取整個文件,然后對其進行解析。 我已經利用了Stig的示例,如下所述: SBJson4Parser示例

   SBJson4ValueBlock block = ^(id obj, BOOL *stop) {
   NSLog(@"Found: %@", @([obj isKindOfClass:[NSDictionary class]]));
    //contactsData *contact = obj;
    NSDictionary *contact = obj;
    NSLog(@"Contact: %@",contact);
   /* NSString *fName, *lName;
    fName = [contact objectForKey:@"mFirstName"];
     lName = [contact objectForKey:@"mLastName"];
    NSLog(@"First Name: %@",fName);
    NSLog(@"Last Name: %@",lName);
    */
};

SBJson4ErrorBlock eh = ^(NSError* err){
    NSLog(@"Oops: %@",error);
};
NSLog(@"Parse work");
id parser = [SBJson4Parser multiRootParserWithBlock:block
                                       errorHandler:eh];
//uint8_t buf[1024];
//unsigned int len = 0;
NSLog(@"Trying to push stream to data");
//[inputStream read:buf maxLength:len];
NSData *data = [NSData dataWithContentsOfFile:filePath options:NSUTF8StringEncoding error:NULL];
//id data = [json da:NSUTF8StringEncoding];
SBJson4ParserStatus status = [parser parse:data];

NSLog(@"Status: %u",status);

如今,借助社交網絡,人們似乎已經擁有數百甚至數千個聯系人。 這會導致iOS設備上的內存占用量更大嗎? 如果是這樣,如何解析流中的單個對象? 如果我必須使用一個委托,將不勝感激。

請注意,我對iOS開發以及Objective-C都是陌生的。

The structure of the json file in question:
{
  "mAddresses": [
  ],
  "mContactPhoto": "",
  "mDisplayName": ",tarun,,,,israni,,", 
  "mPhoneNumberList": [
    {
      "mLabel": "_$!<Home>!$_",
      "mNumber": "(988) 034-5678",
      "mType": 1
    }
  ]
}{
  "mAddresses": [
  ],
  "mContactPhoto": "",
  "mDisplayName": ",Sumit,,,,Kumar,,",
  "mPhoneNumberList": [
    {
      "mLabel": "_$!<Home>!$_",
      "mNumber": "(789) 034-5123",
      "mType": 1
    }
  ]
}

您的解決方案似乎應該對我有用。 如果您的文件太大而又不想將其全部保存在內存中,即您想避免以下行:

NSData *data = [NSData dataWithContentsOfFile:filePath options:NSUTF8StringEncoding error:NULL];

那么您可以使用NSInputStream(未經測試,但希望您能理解):

id parser = [SBJson4Parser multiRootParserWithBlock:block
                                       errorHandler:eh];

id is = [NSInputStream inputStreamWithFileAtPath:filePath];
[is open];

// buffer to read from the input stream
uint8_t buf[1024];

// read from input stream until empty, or an error;
// better error handling is left as an exercise for the reader
while (0 > [is read:buffer maxLength: sizeof buffer]) {
    SBJson4ParserStatus status = [parser parse:data];
    NSLog(@"Status: %u",status);
    // handle parser errors here
}
[is close];

但是,您仍然必須閱讀並解析整個文件,以確保找到特定的聯系人。 無法通過這種方式僅閱讀特定的聯系人。 如果您經常這樣做,則可能需要以其他方式存儲聯系人以更好地支持這種情況。 一種方法是使用例如SQLLite。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM