创建自定义JSON STRING

时间:2016-09-01 06:45:23

标签: ios json

我想使用JSON字符串向服务器发送数据。以下是我想要使用的JSON对象的格式。请帮我创建这种类型的结构。

{ '__metadata': { 'type': 'SP.Data.MetrolinkVerificationListItem' },
                    'Company': 'SOCALGAS-15',
                    'Date': '08/31/2016',
                    'Employee_x0020_ID': '545',
                    'Month': 'JULY',
                    'Name_x0020_of_x0020_Transit': 'METROLINK',
                    'Total_x0020_Amount_x0020_Spent': '444',
                    'Year': '2015'}

2 个答案:

答案 0 :(得分:1)

如果您想在请求中传递NSDictionary作为参数,请使用此

NSDictionary *type = @{ @"type" : @"SP.Data.MetrolinkVerification‌​ListItem"
                       };

NSDictionary *final = @{@"metadata" : type, @"pas" : @"1234",@"name" : @"hai"
                       };

NSLog(@"json string %@",final);

<强>输出

enter image description here

如果您想将NSDictionary传递给JSON String作为您的请求的参数,请使用此

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:final
                                                   options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];

if (! jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

     NSLog(@"final %@",jsonString);
}

<强>输出

enter image description here

答案 1 :(得分:0)

您可以使用NSString的stringWithFormat

NSString *str = [NSString stringWithFormat:@"{ '__metadata': { 'type': '%@' },'Company': '%@','Date': '%@','Employee_x0020_ID': '%@','Month': '%@','Name_x0020_of_x0020_Transit': '%@','Total_x0020_Amount_x0020_Spent': '%@','Year': '%@'}",typeStr,companyStr,dateStr,employeeIDStr,monthStr,nameTransitStr,amountSpentStr,yearStr];

如果要用NSInteger替换字符串,请将%@替换为%ld