-什么是JSON;
以上四个图分别解析了json的结构流程,数组,字典(object),以及用各种操作语言将字符串,数组,和字典套用在一起,条理性较强,具体含义将在下面一一阐述;
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。
下面是一个具体的JSON数据:
{"code": "cn","cities": [{"name": "保定", "lat": 38849998, "lon": 115569999},{"name": "北京", "lat": 39930000, "lon": 116279998, "selected": true},{"name": "沈阳", "lat": 41770000, "lon": 123430000},{"name": "成都", "lat": 30670000, "lon": 104019996},{"name": "大连", "lat": 38900001, "lon": 121629997},{"name": "福州", "lat": 26079999, "lon": 119279998},{"name": "阜阳", "lat": 32930000, "lon": 115830001},{"name": "赣州", "lat": 25850000, "lon": 114949997},{"name": "广州", "lat": 23129999, "lon": 113319999},{"name": "贵阳", "lat": 26579999, "lon": 106720001},{"name": "哈尔滨", "lat": 45750000, "lon": 126769996},{"name": "海口", "lat": 20030000, "lon": 110349998},{"name": "邯郸", "lat": 38029998, "lon": 114419998},{"name": "杭州", "lat": 30229999, "lon": 120169998},{"name": "合肥", "lat": 31870000, "lon": 117230003},{"name": "菏泽", "lat": 36119998, "lon": 114370002},{"name": "衡阳", "lat": 36119998, "lon": 114370002},{"name": "呼和浩特", "lat": 40819999, "lon": 111680000},{"name": "黄冈", "lat": 30620000, "lon": 114129997},{"name": "济南", "lat": 36680000, "lon": 116980003},{"name": "济宁", "lat": 36680000, "lon": 116980003},{"name": "昆明", "lat": 25020000, "lon": 102680000},{"name": "拉萨", "lat": 29657589, "lon": 91132050},{"name": "兰州", "lat": 36040000, "lon": 103879997},{"name": "南昌", "lat": 28600000, "lon": 115919998},{"name": "南充", "lat": 30799999, "lon": 106080001},{"name": "南京", "lat": 32000000, "lon": 118800003},{"name": "南宁", "lat": 22819999, "lon": 108349998},{"name": "南通", "lat": 32000000, "lon": 118800003},{"name": "南阳", "lat": 33029998, "lon": 112580001},{"name": "宁波", "lat": 30229999, "lon": 120169998},{"name": "青岛", "lat": 36069999, "lon": 120330001},{"name": "厦门", "lat": 24479999, "lon": 118080001},{"name": "汕头", "lat": 23399999, "lon": 116680000},{"name": "商丘", "lat": 36119998, "lon": 114370002},{"name": "上海", "lat": 31399999, "lon": 121470001},{"name": "邵阳", "lat": 27229999, "lon": 111470001},{"name": "深圳", "lat": 22549999, "lon": 114099998},{"name": "石家庄", "lat": 38029998, "lon": 114419998},{"name": "太原", "lat": 37779998, "lon": 112550003},{"name": "唐山", "lat": 39669998, "lon": 118150001},{"name": "天津", "lat": 39099998, "lon": 117169998},{"name": "潍坊", "lat": 36700000, "lon": 119080001},{"name": "温州", "lat": 30229999, "lon": 120169998},{"name": "乌鲁木齐", "lat": 43779998, "lon": 87620002},{"name": "武汉", "lat": 30620000, "lon": 114129997},{"name": "西安", "lat": 34299999, "lon": 108930000},{"name": "西宁", "lat": 36619998, "lon": 101769996},{"name": "信阳", "lat": 32130001, "lon": 114050003},{"name": "徐州", "lat": 34279998, "lon": 117150001},{"name": "盐城", "lat": 34279998, "lon": 117150001},{"name": "宜宾", "lat": 28799999, "lon": 104599998},{"name": "银川", "lat": 38479999, "lon": 106220001},{"name": "长春", "lat": 43900001, "lon": 125220001},{"name": "长沙", "lat": 28229999, "lon": 112870002},{"name": "郑州", "lat": 34720001, "lon": 113650001},{"name": "重庆", "lat": 29520000, "lon": 106480003},{"name": "周口", "lat": 33000000, "lon": 114019996},{"name": "驻马店", "lat": 33000000, "lon": 114019996}]}
二,JSON的解析针对与OC;
-(void)cityJOSON{
// 取出JSON 数据?
NSString * path = [[NSBundle mainBundle] pathForResource:@"citys" ofType:@"txt"];
NSDictionary * arr = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableContainers error:Nil];
NSLog(@"取出字典的内容%@",arr);
[_tableArr addObjectsFromArray:[arr objectForKey:@"cities"]];
NSLog(@"取出字典中所有的城市%@",_tableArr);
NSLog(@"答应出城市的个数%d",_tableArr.count);
// + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
NSError * error = nil;
NSData * obdata = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString * str = [[[NSString alloc] initWithData:obdata encoding:NSUTF8StringEncoding]autorelease];
NSLog(@"ciciciciciistr %@",str);
[_tableView reloadData];
}
这就用到了JSONKIT.H and JSONKIT.M 的头文件导入, 引用里面的实现方法和Json 特有属性的操作;
下面对
JSONKIT.H 进行翻译初步了解,在UI中实现
typedef NSUInteger JKFlags;
/*
JKParseOptionComments : Allow C style // and /_* ... *_/ (without a _, obviously) comments in JSON.
JKParseOptionUnicodeNewlines : Allow Unicode recommended (?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}]) newlines.
JKParseOptionLooseUnicode : Normally the decoder will stop with an error at any malformed Unicode.
This option allows JSON with malformed Unicode to be parsed without reporting an error.
Any malformed Unicode is replaced with \uFFFD, or "REPLACEMENT CHARACTER".
*/
enum {
JKParseOptionNone = 0,
JKParseOptionStrict = 0,
JKParseOptionComments = (1 <<0),
JKParseOptionUnicodeNewlines = (1 <<1),
JKParseOptionLooseUnicode = (1 <<2),
JKParseOptionPermitTextAfterValidJSON = (1 <<3),
JKParseOptionValidFlags = (JKParseOptionComments | JKParseOptionUnicodeNewlines | JKParseOptionLooseUnicode | JKParseOptionPermitTextAfterValidJSON),
};
typedef JKFlags JKParseOptionFlags;
enum {
JKSerializeOptionNone = 0,
JKSerializeOptionPretty = (1 <<0),
JKSerializeOptionEscapeUnicode = (1 <<1),
JKSerializeOptionEscapeForwardSlashes = (1 <<4),
JKSerializeOptionValidFlags = (JKSerializeOptionPretty | JKSerializeOptionEscapeUnicode | JKSerializeOptionEscapeForwardSlashes),
};
typedef JKFlags JKSerializeOptionFlags;
#ifdef __OBJC__
typedef struct JKParseState JKParseState;// Opaque internal, private type.
// As a general rule of thumb, if you use a method that doesn't accept a JKParseOptionFlags argument, it defaults to JKParseOptionStrict
@interface JSONDecoder : NSObject {
JKParseState *parseState;
}
+ (id)decoder;
+ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (void)clearCache;
// The parse... methods were deprecated in v1.4 in favor of the v1.4 objectWith... methods.
- (id)parseUTF8String:(constunsigned char *)string length:(size_t)length JK_DEPRECATED_ATTRIBUTE;// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead.
- (id)parseUTF8String:(constunsigned char *)string length:(size_t)length error:(NSError **)error JK_DEPRECATED_ATTRIBUTE;// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead.
// The NSData MUST be UTF8 encoded JSON.
- (id)parseJSONData:(NSData *)jsonData JK_DEPRECATED_ATTRIBUTE;// Deprecated in JSONKit v1.4. Use objectWithData: instead.
- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error JK_DEPRECATED_ATTRIBUTE;// Deprecated in JSONKit v1.4. Use objectWithData:error: instead.
// Methods that return immutable collection objects.
- (id)objectWithUTF8String:(constunsigned char *)string length:(NSUInteger)length;
- (id)objectWithUTF8String:(constunsigned char *)string length:(NSUInteger)length error:(NSError **)error;
// The NSData MUST be UTF8 encoded JSON.
- (id)objectWithData:(NSData *)jsonData;
- (id)objectWithData:(NSData *)jsonData error:(NSError **)error;
// Methods that return mutable collection objects.
- (id)mutableObjectWithUTF8String:(constunsigned char *)string length:(NSUInteger)length;
- (id)mutableObjectWithUTF8String:(constunsigned char *)string length:(NSUInteger)length error:(NSError **)error;
// The NSData MUST be UTF8 encoded JSON.
- (id)mutableObjectWithData:(NSData *)jsonData;
- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error;
@end
#pragma mark Deserializing methods
@interface NSString (JSONKitDeserializing)
- (id)objectFromJSONString;
- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
- (id)mutableObjectFromJSONString;
- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
@end
@interface NSData (JSONKitDeserializing)
// The NSData MUST be UTF8 encoded JSON.
- (id)objectFromJSONData;
- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
- (id)mutableObjectFromJSONData;
- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
@end
#pragma mark Serializing methods
@interface NSString (JSONKitSerializing)
// Convenience methods for those that need to serialize the receiving NSString (i.e., instead of having to serialize a NSArray with a single NSString, you can "serialize to JSON" just the NSString).
// Normally, a string that is serialized to JSON has quotation marks surrounding it, which you may or may not want when serializing a single string, and can be controlled with includeQuotes:
// includeQuotes:YES `a "test"...` -> `"a \"test\"..."`
// includeQuotes:NO `a "test"...` -> `a \"test\"...`
- (NSData *)JSONData; // Invokes JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
- (NSString *)JSONString; // Invokes JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
@end
@interface NSArray (JSONKitSerializing)
- (NSData *)JSONData;
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
- (NSString *)JSONString;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
@end
@interface NSDictionary (JSONKitSerializing)
- (NSData *)JSONData;
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
- (NSString *)JSONString;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
@end
#ifdef __BLOCKS__
@interface NSArray (JSONKitSerializingBlockAdditions)
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
@end
@interface NSDictionary (JSONKitSerializingBlockAdditions)
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
@end
#endif
#endif // __OBJC__
#endif // _JSONKIT_H_
#ifdef __cplusplus
} // extern "C"
#endif
这相当于引入第三方类,我们可以调用其中的方法,以达到我们第三方提供的效果。预先调用第三方类中的方法,我们就得对JSON的原理了如指掌,以及其自带操作命令;
1,赋值给变量
可以创建一个新的 JavaScript 变量,然后将 JSON 格式的数据字符串直接赋值给它:
2,访问数据
尽管看起来不明显,但是上面的长字符串实际上只是一个
数组;将这个数组放进 JavaScript
变量之后,就可以很轻松地访问它。实际上,只需用点号表示法来表示
数组元素。所以,要想访问 programmers 列表的第一个条目的姓氏,只需在 JavaScript 中使用下面这样的代码:
1
|
people.programmers[0].lastName;
|
注意,
数组索引是从零开始的。所以,这行代码首先访问 people
变量中的数据;然后移动到称为 programmers的条目,再移动到第一个记录([0]);最后,访问 lastName键的值。结果是字符串值 “McLaughlin”。
下面是使用同一
变量的几个示例。
1
2
3
|
people.authors[1].genre
// Value is "fantasy"
people.musicians[3].lastName
// Undefined. This refers to the fourth entry, and there isn't one
people.programmers[2].firstName
// Value is "Elliotte"
|
利用这样的语法,可以处理任何 JSON 格式的数据,而不需要使用任何额外的 JavaScript 工具包或 API。
修改数据
正如可以用点号和方括号访问数据,也可以按照同样的方式轻松地修改数据:
1
|
people.musicians[1].lastName =
"Rachmaninov"
;
|
在将字符串转换为 JavaScript 对象之后,就可以像这样修改
变量中的数据。
换回字符串
当然,如果不能轻松地将对象转换回本文提到的文本格式,那么所有
数据修改都没有太大的价值。在 JavaScript 中这种转换也很简单:
1
|
var
newJSONtext = people.toJSONString();
|
这样就就获得了一个可以在任何地方使用的
文本字符串,例如,可以将它用作 Ajax 应用程序中的请求字符串。
更重要的是,可以将 任何JavaScript 对象转换为 JSON 文本。并非只能处理原来用 JSON 字符串赋值的
变量。为了对名为 myObject的对象进行转换,只需执行相同形式的命令:
1
|
var
myObjectInJSON = myObject.toJSONString();
|
这就是 JSON 与本系列讨论的其他数据格式之间最大的差异。如果使用 JSON,只需调用一个简单的函数,就可以获得经过格式化的数据,可以直接使用了。对于其他数据格式,需要在
原始数据和格式化数据之间进行转换。即使使用 Document Object Model 这样的 API(提供了将自己的数据结构转换为文本的函数),也需要学习这个 API 并使用 API 的对象,而不是使用原生的 JavaScript 对象和语法。
最终结论是,如果要处理大量 JavaScript 对象,那么 JSON 是一个好选择,这样就可以轻松地将数据转换为可以在请求中发送给服务器端程序的格式。