This repository has been archived by the owner on Jun 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
MCJSONDataTransformer.j
115 lines (98 loc) · 2.58 KB
/
MCJSONDataTransformer.j
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* MCJSONDataTransformer.j
* MCResource
*
* Created by Joachim Garth
* Copyright 2011, Monkey & Company UG (haftungsbeschränkt)
*
* This class is an example implementation of a CPDictionary -> FormData and JSON -> CPDictionary transformer.
* Nothing more, nothing less.
*
*/
@implementation MCJSONDataTransformer : CPObject
// Transforms a CPDictionary into a FormData object
- (JSObject)transformedData:(id)data
{
_formData = new FormData();
if(!data)
{
return nil;
}
[self _fillFormData:_formData withData:data prefix:nil];
return _formData;
}
// Transform a JSON-String to a CPDictionary / CPArray
- (CPDictionary)reverseTransformedData:(CPString)data
{
if([data length] > 0 && ![data isEqualToString:@" "])
{
try
{
var parsedObject = JSON.parse(data);
if (parsedObject)
{
if(parsedObject.isa && [parsedObject isKindOfClass:[CPArray class]])
{
var returnArray = [CPArray new],
enumerator = [parsedObject objectEnumerator],
item;
while(item = [enumerator nextObject])
{
[returnArray addObject:[CPDictionary dictionaryWithJSObject:item recursively:YES]];
}
return returnArray;
}
else
{
return [CPDictionary dictionaryWithJSObject:parsedObject recursively:YES];
}
}
}
catch (anyException)
{
throw [MCError errorWithDescription:@"Could not reverse transform the following data: '" + data + "'"];
}
}
}
#pragma mark -
#pragma mark Internal Methods
/*
* This method recursively iterates through a CPDictionary and
* saves all its values in a passed-in FormData object
*/
- (void)_fillFormData:(JSObject)aFormData withData:(CPDictionary)data prefix:(CPString)prefix
{
var keyEnumerator = [data keyEnumerator],
currentKey;
while(currentKey = [keyEnumerator nextObject])
{
var currentValue = [data valueForKey:currentKey];
if(currentValue.isa && [currentValue isKindOfClass:[CPDate class]])
{
currentValue = [currentValue ISO8601String];
}
if(currentValue.isa && [currentValue isKindOfClass:[CPNull class]])
{
currentValue = null;
}
// Recurse if neccessary
if(currentValue && currentValue.isa && [currentValue isKindOfClass:[CPDictionary class]])
{
// This must get triggered on the first loop
if(!prefix)
{
prefix = currentKey;
[self _fillFormData:aFormData withData:currentValue prefix:prefix];
}
else
{
[self _fillFormData:aFormData withData:currentValue prefix:prefix + "[" + currentKey + "]"];
}
}
else
{
aFormData.append(prefix + "[" + currentKey + "]", currentValue);
}
}
}
@end