目前,我的iPhone应用程序中包含一个URL,其中包含一个我必须解析的JSON对象。
我能够获取JSON对象,将对象转换为NSString,现在问题是解析对象/ NSString对象。
我目前正在使用SBJSON。
如何使用SBJSON框架迭代JSON对象的关键元素?
{
"status":"SUCCESS",
"fields":[
{
"type":"instant",
"field":"GenerationPower",
"label":"now",
JSON对象比这些键和关键元素大得多,但是一旦解决了这个问题,我肯定JSON对象的其余部分将很容易,因为我将有一个引用。
谢谢Stackoverflow!
修改 这里有一些代码来澄清我的问题。
+ (NSString *) pullingInfo
{
NSURL *solarWebURL = [NSURL URLWithString:myurl];
if (solarWebURL)
{
NSLog(@"Calling: %@", solarWebURL);
NSData *jsonData = [NSData dataWithContentsOfURL:solarWebURL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
NSString* errorMessage = @"Error reading URL";
return errorMessage;
}
+ (NSDictionary *) jsonDictionaryObject
{
NSDictionary * jsonDictionary = [[NSDictionary alloc] init];
NSString * monroeString = [MonroeParser pullingInfo];
return jsonDictionary;
}
正如我之前所说,我已经将JSON对象加载到NSString对象“jsonString”中。现在我想开始解析字符串。
我想我甚至可能不需要使用JSON的框架进行解析,我可能只是使用Apple提供的NSString约定来解析NSString。
有什么想法吗?但也许这效率不高......
答案 0 :(得分:1)
您正在使用SBJSON,为什么甚至将NSData转换为NSString?您可以使用SBJSONParser的-objectWithData
方法直接将NSData读入NSDictionary。
http://sbjson.org/api/3.2/Classes/SBJsonParser.html#//api/name/objectWithData:
让pullInfo返回一个id。并且在调用函数时检查id是NSDictionary类型还是NSArray类型并进行相应的解析。