瀏覽代碼

Allow customizing content type for JSON responses

Pierre-Olivier Latour 11 年之前
父節點
當前提交
223bc4ba16
共有 2 個文件被更改,包括 11 次插入1 次删除
  1. 2 0
      CGDWebServer/GCDWebServerResponse.h
  2. 9 1
      CGDWebServer/GCDWebServerResponse.m

+ 2 - 0
CGDWebServer/GCDWebServerResponse.h

@@ -63,10 +63,12 @@
 + (GCDWebServerDataResponse*)responseWithHTML:(NSString*)html;
 + (GCDWebServerDataResponse*)responseWithHTMLTemplate:(NSString*)path variables:(NSDictionary*)variables;
 + (GCDWebServerDataResponse*)responseWithJSONObject:(id)object;
++ (GCDWebServerDataResponse*)responseWithJSONObject:(id)object contentType:(NSString*)type;
 - (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;
+- (id)initWithJSONObject:(id)object contentType:(NSString*)type;
 @end
 
 @interface GCDWebServerFileResponse : GCDWebServerResponse

+ 9 - 1
CGDWebServer/GCDWebServerResponse.m

@@ -215,6 +215,10 @@
   return ARC_AUTORELEASE([[self alloc] initWithJSONObject:object]);
 }
 
++ (GCDWebServerDataResponse*)responseWithJSONObject:(id)object contentType:(NSString*)type {
+  return ARC_AUTORELEASE([[self alloc] initWithJSONObject:object contentType:type]);
+}
+
 - (id)initWithText:(NSString*)text {
   NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];
   if (data == nil) {
@@ -246,12 +250,16 @@
 }
 
 - (id)initWithJSONObject:(id)object {
+  return [self initWithJSONObject:object contentType:@"application/json"];
+}
+
+- (id)initWithJSONObject:(id)object contentType:(NSString*)type {
   NSData* data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL];
   if (data == nil) {
     ARC_RELEASE(self);
     return nil;
   }
-  return [self initWithData:data contentType:@"application/json"];
+  return [self initWithData:data contentType:type];
 }
 
 @end