我需要将一个 json 字符串解析为一个 NSMutableArray...我是这样做的:
JsonString = "{
"list":[
{
"IDI":{
"IDI_ID":1
},
"PAR_VPARAM":"param1",
"PAR_VALUE":"value1"
},
{
"IDI":{
"IDI_ID":2
},
"PAR_VPARAM":"param2",
"PAR_VALUE":"value2"
},
{
"IDI":{
"IDI_ID":3
},
"PAR_VPARAM":"param3",
"PAR_VVALUE":"value3"
}
]
}";
NSData *data = [JsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
NSMutableArray *resultArray = [json objectForKeyedSubscript:@"list"];
我有一个名为 PARAMETERS 的对象,它具有与 JSON 的单个项目相同的结构:“列表”。当我解析它时,它起作用了,问题出在 json 中每个项目内部的对象中:“IDI”,总是用空值解析。
for(NSObject *obj in resultArray){
Parameters *paritem = (Parameters *)obj;
int test = paritem.IDI.IDI_ID; //Error here!
}
我该怎么做?
最佳答案
NSJSONSerialization
不会将您的 JSON 数据映射到您的自定义类。它将提供 NSString
、NSNumber
、NSDictionary
和 NSArray
对象(或者它们的可变对象,如果您指定对 NSJSONReadingOptions
)。
如果您想将此数据映射到您的 Parameters
类,您必须自己提供该逻辑。您不能简单地转换 NSDictionary
。
for(NSObject *obj in resultArray){
Parameters *paritem = [[Parameters alloc] init];
paritem.PAR_VPARAM = obj[@"PAR_VPARAM"];
paritem.PAR_VALUE = obj[@"PAR_VALUE"];
// To capture the IDI property, you will either have to
// define a new IDI class with a property named "IDI_ID",
// live with NSDictionary, or add an "IDI_ID" property
// to your Parameters class.
// In this example, I left the value as a dictionary.
paritem.IDI = obj[@"IDI"];
// Here's how you would get the IDI_ID:
NSNumber *IDI_ID = paritem.IDI[@"IDI_ID"];
}
顺便提一下,这里有一些不请自来的风格提示:
- 对于 Obj-C 中的变量和属性,lowerCamelCase 是常规的。代替
paritem.PAR_VPARAM
,使用parItem.parVParam
(注意parItem
中的大写I
)。 - 您的类名应该有两个或三个字母的“命名空间”(很像
NSString
、UIView
或CGPoint
)。如果您不能想出几个字母来代表这个特定项目,请使用您公司名称的缩写。如果一切都失败了,请使用您的姓名首字母。 - 您的参数名称非常模糊,而且有些多余。真的每个属性都需要以
PAR_
为前缀吗?您真的需要将IDI_ID
嵌套在Parameters
对象的IDI
属性中吗?您可以通过更加简洁来提高代码的可读性。
如果您采纳了这个建议(我对您的源数据做了一些假设),您的代码可能如下所示:
for(NSObject *obj in resultArray){
APParameters *parItem = [[APParameters alloc] init];
parItem.parameterName = obj[@"PAR_VPARAM"];
parItem.parameterValue = obj[@"PAR_VALUE"];
// To capture the IDI property, you will either have to
// define a new IDI class with a property named "IDI_ID",
// live with NSDictionary, or add a property to your
// Parameters class which holds the IDI_ID value directly.
// In this example, I grabbed the IDI_ID value directly.
parItem.itemID = obj[@"IDI"][@"IDI_ID"];
}
关于ios - Objective-C 将 json 解析为对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24062890/