来 self 的 iOS 应用程序的发布请求如下所示:
Request: {“pod_id”:“F11",“type”:“Normal Activity”,“time_stamp”:“2019-0417T22:29:35.14Z”,“url”:“https:\/\/s3.amazonaws.com\/****\/******\/2019-04-17\/*******-22:29:35.json”}
但是后端/rest-api 需要以下格式的 JSON 文件:
The request body should be a "application/json" encoded object, containing the following items.
Parameter Description
name
time_stamp
duration
type
请求的格式是否必须与后端服务器期望的格式相同?
这是我作为 iOS 成员工作的项目之一,我们有一个正在扩展 REST API 的后端团队。我需要通过从 iOS 应用程序收集数据来发布数据到 http://asdasdasd/api/post-act 。但正如前面提到的,它期望的格式与我传递的格式不同,因此我不断收到 400 错误。我对其进行了更改,以便直接传递 JSON,即来自上述请求的 url 的 JSON,但它的字段与后端预期的 JSON 不同。
/*request-setup
void)setupRequestManager {
self.afRequestManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:EndPointBaseURL]];
self.afRequestManager.responseSerializer = [AFJSONResponseSerializer serializer];
self.afRequestManager.requestSerializer = [AFJSONRequestSerializer serializer];
最佳答案
按如下方式设计您的请求结构。
swift
struct Request: Codable {
let podID, type, timeStamp: String
let url: String
enum CodingKeys: String, CodingKey {
case podID = "pod_id"
case type
case timeStamp = "time_stamp"
case url
}
}
创建一个 Struct 对象并设置所有值。将请求对象传递给 API 时对请求对象进行 JSON 编码,如下所示。
let httpBody = try JSONEncoder().encode(request)
apiRequest.body = httpBody
确保 ApiRequest header 中的 Content-Type 设置为“application/json”
Content-Type : application/json
通过这种方式,您可以在 REST API 调用中将 JSON 作为请求传递。
Objective-C
Request.h
@class TESTRequest;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - Object interfaces
@interface TESTRequest : NSObject
@property (nonatomic, copy) NSString *podID;
@property (nonatomic, copy) NSString *type;
@property (nonatomic, copy) NSString *timeStamp;
@property (nonatomic, copy) NSString *url;
+ (_Nullable instancetype)fromJSON:(NSString *)json encoding:(NSStringEncoding)encoding error:(NSError *_Nullable *)error;
+ (_Nullable instancetype)fromData:(NSData *)data error:(NSError *_Nullable *)error;
- (NSString *_Nullable)toJSON:(NSStringEncoding)encoding error:(NSError *_Nullable *)error;
- (NSData *_Nullable)toData:(NSError *_Nullable *)error;
@end
NS_ASSUME_NONNULL_END
请求.m
NS_ASSUME_NONNULL_BEGIN
#pragma mark - Private model interfaces
@interface TESTRequest (JSONConversion)
+ (instancetype)fromJSONDictionary:(NSDictionary *)dict;
- (NSDictionary *)JSONDictionary;
@end
#pragma mark - JSON serialization
TESTRequest *_Nullable TESTRequestFromData(NSData *data, NSError **error)
{
@try {
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];
return *error ? nil : [TESTRequest fromJSONDictionary:json];
} @catch (NSException *exception) {
*error = [NSError errorWithDomain:@"JSONSerialization" code:-1 userInfo:@{ @"exception": exception }];
return nil;
}
}
TESTRequest *_Nullable TESTRequestFromJSON(NSString *json, NSStringEncoding encoding, NSError **error)
{
return TESTRequestFromData([json dataUsingEncoding:encoding], error);
}
NSData *_Nullable TESTRequestToData(TESTRequest *request, NSError **error)
{
@try {
id json = [request JSONDictionary];
NSData *data = [NSJSONSerialization dataWithJSONObject:json options:kNilOptions error:error];
return *error ? nil : data;
} @catch (NSException *exception) {
*error = [NSError errorWithDomain:@"JSONSerialization" code:-1 userInfo:@{ @"exception": exception }];
return nil;
}
}
NSString *_Nullable TESTRequestToJSON(TESTRequest *request, NSStringEncoding encoding, NSError **error)
{
NSData *data = TESTRequestToData(request, error);
return data ? [[NSString alloc] initWithData:data encoding:encoding] : nil;
}
@implementation TESTRequest
+ (NSDictionary<NSString *, NSString *> *)properties
{
static NSDictionary<NSString *, NSString *> *properties;
return properties = properties ? properties : @{
@"pod_id": @"podID",
@"type": @"type",
@"time_stamp": @"timeStamp",
@"url": @"url",
};
}
+ (_Nullable instancetype)fromData:(NSData *)data error:(NSError *_Nullable *)error
{
return TESTRequestFromData(data, error);
}
+ (_Nullable instancetype)fromJSON:(NSString *)json encoding:(NSStringEncoding)encoding error:(NSError *_Nullable *)error
{
return TESTRequestFromJSON(json, encoding, error);
}
+ (instancetype)fromJSONDictionary:(NSDictionary *)dict
{
return dict ? [[TESTRequest alloc] initWithJSONDictionary:dict] : nil;
}
- (instancetype)initWithJSONDictionary:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
- (void)setValue:(nullable id)value forKey:(NSString *)key
{
id resolved = TESTRequest.properties[key];
if (resolved) [super setValue:value forKey:resolved];
}
- (NSDictionary *)JSONDictionary
{
id dict = [[self dictionaryWithValuesForKeys:TESTRequest.properties.allValues] mutableCopy];
// Rewrite property names that differ in JSON
for (id jsonName in TESTRequest.properties) {
id propertyName = TESTRequest.properties[jsonName];
if (![jsonName isEqualToString:propertyName]) {
dict[jsonName] = dict[propertyName];
[dict removeObjectForKey:propertyName];
}
}
return dict;
}
- (NSData *_Nullable)toData:(NSError *_Nullable *)error
{
return TESTRequestToData(self, error);
}
- (NSString *_Nullable)toJSON:(NSStringEncoding)encoding error:(NSError *_Nullable *)error
{
return TESTRequestToJSON(self, encoding, error);
}
@end
关于ios - 通过 iOS 进行 JSON 请求并在 Rest Web 中进行请求编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55754465/