[英]Objective-C parse json to list of object
我需要將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單個項目“ list”相同的結構。 當我解析它時,它起作用了,問題出在json中每個項目內部的對象中:“ IDI”,始終使用null值進行解析。
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"];
}
有了這些,下面是一些未經請求的樣式提示:
paritem.PAR_VPARAM
,使用parItem.parVParam
(注意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"];
}
首先,如果您不打算在數組中添加或刪除新對象,建議您將JSON
數據而不是NSMutableArray
轉換為NSArray
。
關於"IDI"
索引,由於它們是字典,因此不會像其他索引一樣被解析為字符串。 您還應該手動創建Parameters
對象,而不是直接強制轉換。
一個例子:
// In Parameters.h
@property (nonatomic, strong) NSString *PAR_VPARAM;
@property (nonatomic, strong) NSDictionary *IDI;
然后在解析JSON之后,
for (NSDictionary *obj in resultArray){
Parameters *paritem = [[Parameters alloc] init];
paritem.PAR_VPARAM = [obj valueForKey:@"PAR_VPARAM"];
paritem.IDI = [obj valueForKey:@"IDI"];
int test = (int)[paritem.IDI valueForKey:@"IDI_ID"];
}
這應該工作良好,並且您可以為其他JSON索引創建新屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.