从josn加载数据模型
- (NSArray *)htmls
{
if (!_htmls) {
// JSON文件的路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"help.json" ofType:nil];
// 加载JSON文件
NSData *data = [NSData dataWithContentsOfFile:path];
// 将JSON数据转为NSArray或者NSDictionary
NSArray *dictArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
// 将字典转成模型
NSMutableArray *htmlArray = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
Html *html = [Html htmlWithDict:dict];
[htmlArray addObject:html];
}
_htmls = htmlArray;
}
return _htmls;
typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
NSJSONReadingAllowFragments = (1UL << 2)
} NS_ENUM_AVAILABLE(10_7, 5_0);
typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
NSJSONWritingPrettyPrinted = (1UL << 0)
} NS_ENUM_AVAILABLE(10_7, 5_0);
/* A class for converting JSON to Foundation objects and converting Foundation objects to JSON.
An object that may be converted to JSON must have the following properties:
- Top level object is an NSArray or NSDictionary
- All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
- All dictionary keys are NSStrings
- NSNumbers are not NaN or infinity
/
NS_CLASS_AVAILABLE(10_7, 5_0)
@interface NSJSONSerialization : NSObject {
@private
void reserved[6];
}
NSJSONReadingMutableContainers:返回可变容器,NSMutableDictionary或NSMutableArray。
NSJSONReadingMutableLeaves:返回的JSON对象中字符串的值为NSMutableString,目前在iOS 7上测试不好用,应该是个bug,参见:
http://stackoverflow.com/questions/19345864/nsjsonreadingmutableleaves-option-is-not-working
NSJSONReadingAllowFragments:允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON Fragment。例如使用这个选项可以解析 @“123” 这样的字符串。参见:
http://stackoverflow.com/questions/16961025/nsjsonserialization-nsjsonreadingallowfragments-reading
(BOOL)isValidJSONObject:(id)obj;
// 判断 该实例(obj)是否为JSONObject
// 需满足下面三个条件
// 1.obj 是NSArray 或 NSDictionay 以及他们派生出来的子类
// 2.obj 包含的所有对象是NSString,NSNumber,NSArray,NSDictionary 或NSNull
// 3.NSNumber的对象不能是NaN或无穷大(NSData )dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError *)error;
// 将JSONObject的实例转成NSData
- (id)JSONObjectWithData:(NSData )data options:(NSJSONReadingOptions)opt error:(NSError *)error;
// 将NSData类型的实例转成JSONObject
(NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream )stream options:(NSJSONWritingOptions)opt error:(NSError *)error;
// 将一个JSONObject的实例写入到一个输出流中 返回写入的长度(id)JSONObjectWithStream:(NSInputStream )stream options:(NSJSONReadingOptions)opt error:(NSError *)error;
// 从输入流中读取成JSONObject 并返回