我正在尝试将文本字段数据存储到json的NSDictionary中。我已经用过SBJson了。
{
"fields":[
{
"textFields":[
{
"text":"Congratulations",
"textSize":"12"
},
{
"text":"Best Wishes",
"textSize":"15"
},
{
"text":"Test text",
"textSize":"10"
}
]
},
{
"imageFields":[
{
"image":"test1.jpg",
"width":"200",
"height":"100"
},
{
"image":"test2.jpg",
"width":"200",
"height":"100"
}
]
}
]
}
我的代码:
-(void)readJson{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:@"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:@"textFields"];
NSLog(@" Dictionary %@ ",textFieldsDict );
}
但其输出如下。
Dictionary (
(
{
text = Congratulations;
textSize = 12;
},
{
text = "Best Wishes";
textSize = 15;
},
{
text = "Test text";
textSize = 10;
}
),
"<null>"
)
似乎字典中有两个项目,一个是null。我想将三个文本字段项放入数组中。我该如何解决这个问题。
答案 0 :(得分:3)
valueForKey:
,请使用objectForKey:
。答案 1 :(得分:1)
我正在修改您的代码以便更好地理解
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:@"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:@"textFields"];
NSLog(@" Dictionary %@ ",textFieldsDict );
}
更合适的方式是
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fieldsArr =[jsonDict objectForKey:@"fields"];
for(int i=0;i<[fieldArr count];i++)
{
NSArray *textFieldArr = [fieldArr objectAtIndex: i];
for(int j=0;j<[textFieldArr count];j++)
{
NSDictionary *dicTextField = [textFieldArr objectAtIndex: j];
NSString *text = [dicTextField objectForKey: @"text"];
NSString *textSize = [dicTextField objectForKey: @"textSize"];
}
}
}
快速帮助
将{
视为字典,将[
视为数组。
希望,我对你有帮助。
答案 2 :(得分:1)
作为你的json格式,[jsonDict valueForKey:@&#34; fields&#34;]将返回一个数组而不是字典,所以你的代码必须是
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fields = [jsonDict objectForKey:@"fields"];
NSDictionary *fieldsDict = fields[0];
NSArray *textFieldsDict = [fieldsDict objectForKey:@"textFields"];
答案 3 :(得分:0)
I have corrected the json format and used NSJSONSerialization,
{"fields":
{"textFields":
[ {"text":"Congratulations", "textSize":"12"},
{"text":"Best Wishes", "textSize":"15"},
{"text":"Test text", "textSize":"10"}
],
"imageFields":
[ {"image":"test1.jpg","width":"200", "height":"100"},
{"image":"test2.jpg", "width":"200", "height":"100"}
]
}
}
-(void)readJson
NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSDictionary *fields = [jsonDict objectForKey:@"fields"];
NSArray *textArray=[fields objectForKey:@"textFields"] ;
NSLog(@"--- %@",textArray );
}