OStack程序员社区-中国程序员成长平台

标题: ios - 如何在请求正文中设置对象名称以在 Ios 中解析 json [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 05:37
标题: ios - 如何在请求正文中设置对象名称以在 Ios 中解析 json

我是 JSON 解析的新手,我正在使用以下代码将数据发布到服务器

    NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:ClassicLevel, @"ClassicLevel",CurrentLevel,@"CurrentLevel",UpdatedDate,@"UpdatedDate",Name,@"Name",UpdatedTime,@"UpdatedTime", nil];

    NSError*error;
    //convert object to data
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString"http://testURL"]];
    [request setHTTPMethod"OST"];
    [request setValue"application/json" forHTTPHeaderField"Content-Type"];
    [request setValue"application/json" forHTTPHeaderField"Accept"];
    [request setValue:[NSString stringWithFormat"%d", [jsonData length]] forHTTPHeaderField"Content-Length"];

    [request setHTTPBody:jsonData];

通过使用它,我可以生成以下请求正文

{
 "Name":"abc",
 "UpdatedDate":"",
 "CurrentLevel":"2",
 "UpdatedTime":"122",
 "ClassicLevel":"1" 
}

但我必须生成请求正文,例如:

{
"objTimesheet" : 
    {
    "Name":"abc",
    "UpdatedDate":"",
    "CurrentLevel":"2",
    "UpdatedTime":"122",
    "ClassicLevel":"1" 
    }
}

提前致谢。



Best Answer-推荐答案


您正在字典中寻找字典。放弃你已经拥有的:

NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:ClassicLevel, @"ClassicLevel",CurrentLevel,@"CurrentLevel",UpdatedDate,@"UpdatedDate",Name,@"Name",UpdatedTime,@"UpdatedTime", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:newDatasetInfo, @"objTimesheet", nil];

NSError*error;
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];

关于ios - 如何在请求正文中设置对象名称以在 Ios 中解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20545098/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4