Ios 创建自定义JSON字符串
我想使用JSON字符串向服务器发送数据。下面是我想要使用的JSON对象的格式。请帮助我创建这种类型的结构Ios 创建自定义JSON字符串,ios,json,Ios,Json,我想使用JSON字符串向服务器发送数据。下面是我想要使用的JSON对象的格式。请帮助我创建这种类型的结构 { '__metadata': { 'type': 'SP.Data.MetrolinkVerificationListItem' }, 'Company': 'SOCALGAS-15', 'Date': '08/31/2016', 'Employee_x0020_ID':
{ '__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'}
您可以使用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如果要根据请求将
NSDictionary
作为参数传递,请使用此
NSDictionary *type = @{ @"type" : @"SP.Data.MetrolinkVerificationListItem"
};
NSDictionary *final = @{@"metadata" : type, @"pas" : @"1234",@"name" : @"hai"
};
NSLog(@"json string %@",final);
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);
}
输出
如果要根据请求将
NSDictionary
作为参数传递给JSON字符串
,请使用
NSDictionary *type = @{ @"type" : @"SP.Data.MetrolinkVerificationListItem"
};
NSDictionary *final = @{@"metadata" : type, @"pas" : @"1234",@"name" : @"hai"
};
NSLog(@"json string %@",final);
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);
}
输出
您能否显示您尝试过的代码以及您面临的问题DNSDictionary*dict1=[[NSDictionary alloc]initWithObjects和Keys:@“SP.Data.MetrolinkVerificationListItem”,“type”,nil];NSDictionary*dict2=[[NSDictionary alloc]initWithObjectsAndKeys:@“hai”、@“name”、@“1234”、@“pas”、nil];NSDictionary*myDictionary=[[NSDictionary alloc]initWithObjectsAndKeys:dict2,@“设备”,dict1,@“元数据”,nil];NSString*str=[myDictionary bv_jsonStringWithPrettyPrint:NO];NSLog(@“json字符串%@”,str);