860860}
861861
862862static BOOL
863- writeObject (id obj, NSMutableString *output, NSInteger tabs)
863+ writeObject (id obj, NSMutableString *output, NSInteger tabs, NSJSONWritingOptions opt )
864864{
865865 if ([obj isKindOfClass: NSArrayClass])
866866 {
874874 writeComma = YES ;
875875 writeNewline (output, tabs);
876876 writeTabs (output, tabs);
877- writeObject (o, output, tabs + 1 );
877+ writeObject (o, output, tabs + 1 , opt );
878878 END_FOR_IN (obj)
879879 writeNewline (output, tabs);
880880 writeTabs (output, tabs);
883883 else if ([obj isKindOfClass: NSDictionaryClass])
884884 {
885885 BOOL writeComma = NO ;
886+ NSArray *keys = [obj allKeys ];
886887 [output appendString: @" {" ];
887- FOR_IN (id , o, obj)
888+
889+ if ((opt & NSJSONWritingSortedKeys ) == NSJSONWritingSortedKeys )
890+ {
891+ keys = [keys sortedArrayUsingSelector: @selector (compare: )];
892+ }
893+
894+ FOR_IN (id , o, keys)
888895 // Keys in dictionaries must be strings
889896 if (![o isKindOfClass: NSStringClass]) { return NO ; }
890897 if (writeComma)
894901 writeComma = YES ;
895902 writeNewline (output, tabs);
896903 writeTabs (output, tabs);
897- writeObject (o, output, tabs + 1 );
898- [output appendString: @" : " ];
899- writeObject ([obj objectForKey: o], output, tabs + 1 );
900- END_FOR_IN (obj)
904+ writeObject (o, output, tabs + 1 , opt);
905+ [output appendString: @" :" ];
906+ writeObject ([obj objectForKey: o], output, tabs + 1 , opt);
907+ END_FOR_IN (keys)
908+
901909 writeNewline (output, tabs);
902910 writeTabs (output, tabs);
903911 [output appendString: @" }" ];
@@ -1062,7 +1070,7 @@ + (NSData*) dataWithJSONObject: (id)obj
10621070
10631071 tabs = ((opt & NSJSONWritingPrettyPrinted) == NSJSONWritingPrettyPrinted) ?
10641072 0 : NSIntegerMin;
1065- if (writeObject (obj, str, tabs))
1073+ if (writeObject (obj, str, tabs, opt ))
10661074 {
10671075 data = [str dataUsingEncoding: NSUTF8StringEncoding];
10681076 if (NULL != error)
@@ -1089,7 +1097,7 @@ + (NSData*) dataWithJSONObject: (id)obj
10891097
10901098+ (BOOL ) isValidJSONObject : (id )obj
10911099{
1092- return writeObject (obj, nil , NSIntegerMin);
1100+ return writeObject (obj, nil , NSIntegerMin, 0 );
10931101}
10941102
10951103+ (id ) JSONObjectWithData : (NSData *)data
0 commit comments