Question

Strangely, there doesn't appear to be any public method to serialize an array, yet it can obviously do it when serializing an array property. I have a JSONModel-inherited class with an array property. I want to get a JSON textual representation of just that property, not the whole object.

I don't mind modifying the source, but a head-start as to where to look would be appreciated.

Another thought is to serialize each object individually to JSON and wrap them in [,].

Was it helpful?

Solution

Explanation:

JSONModel model represents a JSON object - it matches JSON keys to a model class's properties. That's why for examples you cannot directly create a JSONModel class that matches a JSON feed whose top object is an array. For example:

[obj1, obj2, obj3, etc ...]

There's just no key to match to a property.

Now what you are asking about is the same situation, but in reverse. You cannot export an NSArray to JSON, because there's no JSONModel to take care of it. If you have a model with one property, which is an NSArray - then it's easy. The property will get mapped to 1 JSON key and the NSArray contents will get exported as its contents.

Solution:

If you have an NSArray containing JSONModel instances, you should use the following method:

NSArray* jsonObjects = [YourModelClass arrayOfDictionariesFromModels: modelObjects];

The line above will take care to properly export model classes to dictionaries, then you can export jsonObjects to JSON by using NSJSONSerialization.

Here's the method's docs:

http://www.jsonmodel.com/docs/Classes/JSONModel.html#//api/name/arrayOfDictionariesFromModels:

OTHER TIPS

It ended up actually being pretty easy to implement myself. Very strange this isn't just included in the library though:

@implementation NSArray (JSONModelExtensions)

- (NSString*)toJSONString {
    NSMutableArray* jsonObjects = [NSMutableArray new];
    for ( id obj in self )
        [jsonObjects addObject:[obj toJSONString]];
    return [NSString stringWithFormat:@"[%@]", [jsonObjects componentsJoinedByString:@","]];
}

@end

Serialization (objects to json text):

NSArray* jsonString = [YourObject arrayOfDictionariesFromModels: yourobjectsArray];

If u dont want a warning u have to give NSArray type to jsonString but it will be a simple JSON so it can be NSString too.

Deserialization: (json text back to objects):

NSArray* objectsAgain = [YourObject arrayOfModelsFromDictionaries: jsonString];

Note that the jsonString given is the same that we got at serialization.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top