summaryrefslogtreecommitdiffstats
path: root/Classes/Source/Experimental/CFilteringJSONSerializer.m
blob: 1ee2a3dd68b1c7d07b6e28b53429becb45ed649b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//
//  CFilteringJSONSerializer.m
//  CouchNotes
//
//  Created by Jonathan Wight on 06/20/10.
//  Copyright 2010 toxicsoftware.com. All rights reserved.
//

#import "CFilteringJSONSerializer.h"

@implementation CFilteringJSONSerializer

@synthesize tests;
@synthesize convertersByName;

- (void)dealloc
    {
    [tests release];
    tests = NULL;
    //
    [convertersByName release];
    convertersByName = NULL;
    //
    [super dealloc];
    }

- (NSData *)serializeObject:(id)inObject error:(NSError **)outError
    {
    NSData *theData = NULL;
    for (JSONConversionTest theTest in self.tests)
        {
        NSString *theName = theTest(inObject);
        if (theName != NULL)
            {
            id theObject = NULL;
            JSONConversionConverter theConverter = [self.convertersByName objectForKey:theName];
            if (theConverter)
                {
                theObject = theConverter(inObject);
                }
                
            if (theObject)
                {
                if ([theObject isKindOfClass:[NSData class]])
                    {
                    theData = theObject;
                    break;
                    }
                else
                    {
                    NSError *theError = NULL;
                    theData = [super serializeObject:theObject error:&theError];
                    if (theData != NULL)
                        {
                        break;
                        }
                    }
                }
            }
        }
        
    if (theData == NULL)
        {
        theData = [super serializeObject:inObject error:outError];
        }
        
    return(theData);
    }

- (void)addTest:(JSONConversionTest)inTest
    {
    inTest = [[inTest copy] autorelease];
    NSSet *theTests = [self.tests setByAddingObject:inTest];
    self.tests = theTests;
    }
    
- (void)addConverter:(JSONConversionConverter)inConverter forName:(NSString *)inName
    {
    NSMutableDictionary *theConvertersByName = [[self.convertersByName mutableCopy] autorelease];

    inConverter = [[inConverter copy] autorelease];
    [theConvertersByName setObject:inConverter forKey:inName];
    self.convertersByName = theConvertersByName;
    }
    

@end