FBResponseJSONPayload.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. */
  9. #import "FBResponseJSONPayload.h"
  10. #import "FBLogger.h"
  11. #import "NSDictionary+FBUtf8SafeDictionary.h"
  12. #import "RouteResponse.h"
  13. @interface FBResponseJSONPayload ()
  14. @property (nonatomic, copy, readonly) NSDictionary *dictionary;
  15. @property (nonatomic, readonly) HTTPStatusCode httpStatusCode;
  16. @end
  17. @implementation FBResponseJSONPayload
  18. - (instancetype)initWithDictionary:(NSDictionary *)dictionary
  19. httpStatusCode:(HTTPStatusCode)httpStatusCode
  20. {
  21. NSParameterAssert(dictionary);
  22. if (!dictionary) {
  23. return nil;
  24. }
  25. self = [super init];
  26. if (self) {
  27. _dictionary = dictionary;
  28. _httpStatusCode = httpStatusCode;
  29. }
  30. return self;
  31. }
  32. - (void)dispatchWithResponse:(RouteResponse *)response
  33. {
  34. NSError *error;
  35. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.dictionary
  36. options:NSJSONWritingPrettyPrinted
  37. error:&error];
  38. NSCAssert(jsonData, @"Valid JSON must be responded, error of %@", error);
  39. if (nil == [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]) {
  40. [FBLogger log:@"The incoming data cannot be encoded to UTF-8 JSON. Applying lossy conversion as a workaround."];
  41. jsonData = [NSJSONSerialization dataWithJSONObject:[self.dictionary fb_utf8SafeDictionary]
  42. options:NSJSONWritingPrettyPrinted
  43. error:&error];
  44. }
  45. NSCAssert(jsonData, @"Valid JSON must be responded, error of %@", error);
  46. [response setHeader:@"Content-Type" value:@"application/json;charset=UTF-8"];
  47. [response setStatusCode:self.httpStatusCode];
  48. [response respondWithData:jsonData];
  49. }
  50. @end