소스 검색

Added JSON support to GCDWebServerDataResponse

Pierre-Olivier Latour 11 년 전
부모
커밋
eac83a4d0d
2개의 변경된 파일15개의 추가작업 그리고 0개의 파일을 삭제
  1. 2 0
      CGDWebServer/GCDWebServerResponse.h
  2. 13 0
      CGDWebServer/GCDWebServerResponse.m

+ 2 - 0
CGDWebServer/GCDWebServerResponse.h

@@ -62,9 +62,11 @@
 + (GCDWebServerDataResponse*)responseWithText:(NSString*)text;
 + (GCDWebServerDataResponse*)responseWithHTML:(NSString*)html;
 + (GCDWebServerDataResponse*)responseWithHTMLTemplate:(NSString*)path variables:(NSDictionary*)variables;
++ (GCDWebServerDataResponse*)responseWithJSONObject:(id)object;
 - (id)initWithText:(NSString*)text;  // Encodes using UTF-8
 - (id)initWithHTML:(NSString*)html;  // Encodes using UTF-8
 - (id)initWithHTMLTemplate:(NSString*)path variables:(NSDictionary*)variables;  // Simple template system that replaces all occurences of "%variable%" with corresponding value (encodes using UTF-8)
+- (id)initWithJSONObject:(id)object;
 @end
 
 @interface GCDWebServerFileResponse : GCDWebServerResponse

+ 13 - 0
CGDWebServer/GCDWebServerResponse.m

@@ -211,6 +211,10 @@
   return ARC_AUTORELEASE([[self alloc] initWithHTMLTemplate:path variables:variables]);
 }
 
++ (GCDWebServerDataResponse*)responseWithJSONObject:(id)object {
+  return ARC_AUTORELEASE([[self alloc] initWithJSONObject:object]);
+}
+
 - (id)initWithText:(NSString*)text {
   NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];
   if (data == nil) {
@@ -241,6 +245,15 @@
   return response;
 }
 
+- (id)initWithJSONObject:(id)object {
+  NSData* data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL];
+  if (data == nil) {
+    ARC_RELEASE(self);
+    return nil;
+  }
+  return [self initWithData:data contentType:@"application/json"];
+}
+
 @end
 
 @implementation GCDWebServerFileResponse