如何将JSON解析为Objective C - SBJSON [英] How to parse JSON into Objective C - SBJSON
问题描述
你能否告诉我如何传递一个如下所示的JSON字符串:
Could you please tell me how to pass a JSON String which looks like this:
{"lessons":[{"id":"38","fach":"D","stunde":"t1s1","user_id":"1965","timestamp":"0000-00-00 00:00:00"},{"id":"39","fach":"M","stunde":"t1s2","user_id":"1965","timestamp":"0000-00-00 00:00:00"}]}
我试过这样:
SBJSON *parser =[[SBJSON alloc] init];
NSArray *list = [[parser objectWithString:JsonData error:nil] copy];
[parser release];
for (NSDictionary *stunden in list)
{
NSString *content = [[stunden objectForKey:@"lessons"] objectForKey:@"stunde"];
}
提前感谢
最好的问候
推荐答案
请注意,您的JSON数据具有以下结构:
Note that your JSON data has the following structure:
- 顶级值是一个对象(字典),它有一个名为'lessons'的属性
- 'lessons'属性是一个数组
- 'lessons'数组中的每个元素都是一个对象(包含课程的字典),有几个属性,包括'stunde'
相应的代码是:
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
// 1. get the top level value as a dictionary
NSDictionary *jsonObject = [parser objectWithString:JsonData error:NULL];
// 2. get the lessons object as an array
NSArray *list = [jsonObject objectForKey:@"lessons"];
// 3. iterate the array; each element is a dictionary...
for (NSDictionary *lesson in list)
{
// 3 ...that contains a string for the key "stunde"
NSString *content = [lesson objectForKey:@"stunde"];
}
一些观察结果:
-
在
-objectWithString:错误:
中,错误
参数是指向指针的指针。在这种情况下,更常见的是使用NULL
而不是nil
。 不传递NULL
并使用NSError
对象来检查方法返回时出错nil
In
-objectWithString:error:
, theerror
parameter is a pointer to a pointer. It’s more common to useNULL
instead ofnil
in that case. It’s also a good idea not to passNULL
and use anNSError
object to inspect the error in case the method returnsnil
如果 jsonObject
仅用于该特定方法,您可能不需要复制它。上面的代码没有。
If jsonObject
is used only in that particular method, you probably don’t need to copy it. The code above doesn’t.
这篇关于如何将JSON解析为Objective C - SBJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!