Ich habe diese Methode verwendet,
NSDictionary *jsonObject=[NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(@"jsonObject is %@",jsonObject);
Es wird gedruckt "jsonObject ist null".
Gibt es ein Problem mit "error: nil".
Ich verwende keine URL- oder Verbindungsmethoden.
Ich habe eine Json-Datei und möchte sie in einer Tabelle anzeigen.
Bitte versuchen Sie den folgenden Code.
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:@"loans"];
NSLog(@"loans: %@", latestLoans);
Nur für den Fall, dass jemand hier ist, um den Swift-Code zu sehen:
NSData zu NSDictionary
let dictionary:NSDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(jsonData)! as NSDictionary
NSData zu NSString
let resstr = NSString(data: res, encoding: NSUTF8StringEncoding)
Überprüfen Sie Ihre Json-Eingabe. Könnte es sein, dass Ihr Root-Element weder ein Wörterbuch noch ein Array ist? In der Dokumentation heißt es, dass Sie in diesem Fall NSJSONReadingAllowFragments als Option angeben müssen.
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
NSData *jsonData = [@"{ \"key1\": \"value1\" }" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject=[NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(@"jsonObject is %@",jsonObject);
[p release];
}
Ausgabe:
2012-09-26 16:06:51.610 Untitled[19164:707] jsonObject is {
key1 = value1;
}
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
Dies ist nur eine prägnantere Version des Top-Beitrags.