ontometrics / jsoncoding Goto Github PK
View Code? Open in Web Editor NEWThis is a static library to encode objects to JSON, and decode them back.
This is a static library to encode objects to JSON, and decode them back.
I have some data that is an array containing dictionaries with one key. When trying to decode the data I get an exception. See the following sample data:
"Gms":[{"Id":141635},{"Id":147175},{"Id":146000},{"Id":146205}]
I'd traced down the issue to "decodeArrayOfClass:". There is a line in there that does the following:
if([[innerDictionary allKeys] count] > 1){
innerDictionary = [NSDictionary dictionaryWithObject:[self topJsonObject] forKey:@"object"];
}
Basically, if there is only one key it's being ignored.
However, the fix isn't as simple as changing the conditional. This behavior seems intentional to support a feature I don't really understand. When you encode an array it gets translated to a dictionary with one key where the key is the class and the value is the actual array. So if your JSON input is "List":["one","two"] when you encode it the resulting JSON is "List":[{"__NSCFString":["one","two"]}]
In encodeObject:forKey: there is a conditional that seems to try to suppress this transformation, but as far as I can tell it never works because the conditional is always true:
if(![[className substringToIndex:2] isEqualToString:@"NS"] ||
![[className substringToIndex:2] isEqualToString:@"__"]){
In order for the conditional to fail, the class name would have to start with __ and also start with NS.
In general, it seems like this feature of camelstringing class names and making assuptions about dictionaries with 1 key isn't the way to solve whatever feature is being implemented. Maybe the JSONEncoder also needs something like addAlias so when it runs into that class in arrays and sets it can know how to create the json instead of using some inferred rule that seems to break other types of data.
How does this project differ from
It looks like HRCoder
in particular is very similar.
I have 2 classes:
@interface Message : NSObject <NSCoding>
@property (nonatomic, strong) NSString* command;
@property (nonatomic, strong) MessagePayload* payload;
@end
@interface MessagePayload : NSObject <NSCoding>
@property (nonatomic, strong) NSString* name;
@property (nonatomic, strong) NSString* id;
@end
And the following code serializing and deserializing them:
MessagePayload* payload = [[MessagePayload alloc] init];
payload.name = @"Sample name";
payload.id = @"1234567890";
Message* message = [[Message alloc] init];
message.command = @"Sample command";
message.payload = payload;
NSString* encodedMessage = [JSONEncoder JSONValueOfObject:message];
NSData* jsonData = [encodedMessage dataUsingEncoding:NSUTF8StringEncoding];
Message* decodedMessage = [JSONDecoder decodeWithData:jsonData];
The problem is decodedMessage.payload is nil.
I think I fixed this issue by adding the following line to the JSONEncoder's getEncodingFor: method:
[objectEncoding setObject:[[object class] description] forKey:@"@class"];
Thus, my version of this method is as follows:
- (NSObject *) getEncodingFor:(id) object{
if([objectStack containsObject:object]){
[NSException raise:@"Circular Reference Not Allowed" format:@"Found circular reference for %@ ", object];
}
if([self isValidJSONObject:object]){
return object;
}else{
if ([object isKindOfClass:[NSData class]]) {
return [(NSData *) object base64EncodedString];
}else if ([object isKindOfClass:[NSSet class]]) {
return [self getEncodingForArray:[(NSSet *) object allObjects]];
}else if ([object isKindOfClass:[NSArray class]]) {
return [self getEncodingForArray:(NSArray *) object];
}else if([object isKindOfClass:[NSDate class]]){
return [self getEncodingForDate:(NSDate *) object];
}else{
[self push:object];
[object encodeWithCoder:self];
NSMutableDictionary * objectEncoding = [self topObject];
[objectEncoding setObject:[[object class] description] forKey:@"@class"];
[self pop];
return objectEncoding;
}
}
}
Could you please review this change and let me know if this is a valid fix for the issue?
Thank you in advance!
Not sure why. Also, I wasted a bunch of time on that pluralizer test. Who put that in there as a SenTesting test?? Then someone added the hamcrest defines instead of just having it use the BaseTestCase?? All tests should extend either BaseTestCase or EntityTest.
Just wondering what the status is for Mac support? Intentionally omitted, planned, or waiting for a pull request?
Issue: Deserializing JSON formatted data such as' {"E":0,"D":"{"emptyArray":[]}"} causes a crash in JSONDecoder.m
In decodeArrayOfClass: (Class) class there is no check whether the returned array is empty or not. This causes an out of bounds exception to be thrown.
Code causing exception: innerDictionary = [(NSArray *)[self topJsonObject] objectAtIndex:0];
Adding a check just before seems to do the trick:
NSArray *theArray = (NSArray *) [self topJsonObject];
if ([theArray count] == 0)
return [NSArray new];
Otherwise, kudos for some nice piece of code!
/M
Other open issues on this repo seem to have been fixed. Please mark them (and this one) close. Thanks!
I'm just looking at both options at the minute — does Mantle strictly supersede the capabilities of this library?
This is the obvious way to do JSON, why aren't there 70 million people using this? Is there some type of catch? Or is there some other solution that came out after this?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.