简体   繁体   English

如何在Objective C中使用NSData创建json对象?

[英]How to create json Object with NSData in Objective C?

How to create json Object with NSData in Objective C . 如何在Objective C使用NSData创建json对象。 I'm having values in a NSData variable. 我在NSData变量中有值。

You can use it like this in iOS 5 (if you are sure of your json structure you can directly use NSArray or NSDictionary doing a cast) 您可以在iOS 5中使用它(如果您确定您的json结构,您可以直接使用NSArrayNSDictionary进行演员表)

NSError *jsonError;
id jsonDictionaryOrArray = [NSJSONSerialization JSONObjectWithData:myData options:NULL error:&jsonError];
if(jsonError) {
    // check the error description
    NSLog(@"json error : %@", [jsonError localizedDescription]);
} else {
    // use the jsonDictionaryOrArray
}

if you have a value in NSData object then you can convert it in NSString variable like bellow 如果你在NSData对象中有一个值,那么你可以像在波纹管中那样在NSString变量中转换它

NSString *response = [[NSString alloc] initWithData:receivedData
                                                encoding:NSUTF8StringEncoding];

Edited... 编辑...

i am not sure what you want but i give you the json array from string like bellow.. 我不知道你想要什么,但我给你的字符串像下面的json数组..

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    [responseData release];

    NSError *error;
    SBJSON *json = [[SBJSON new] autorelease];
    NSArray *arrData = [json objectWithString:responseString error:&error];
    [responseString release];

you can get data in array 你可以在数组中获取数据

hope this help you mate... 希望这有助于你交配......

:) :)

NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"youur link"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
if([jsonObjects isKindOfClass:[NSArray class]]){
    //Is array
}else if([jsonObjects isKindOfClass:[NSDictionary class]]){
    //is dictionary
}else{
    //is something else
}

EDIT FOR SWIFT 编辑SWIFT

do {
        if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>] {

        } else {
            print("bad json")
        }
    } catch let error as NSError {
        print(error)
    }

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

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