以下是我必须设置数据的模型。我正在使用数组和字典来实现这一点,这是我尝试过的代码。但它给我的输出是invalid JSON
我想问的另一件事是为什么log of an array starts and ends with small braces?
任何帮助将非常感激。
代码:
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
parameterName,@"parameterName",
parameterType, @"parameterType",
[NSNumber numberWithBool:parameterSorting],@"parameterSorting",[NSNumber numberWithBool:parameterSorting],
@"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = @{@"rqBody":@{@"catalogName":@"",@"userId":@"", @"parameter":paramArray, @"catalogMode":@""}};
NSData *postData = [NSKeyedArchiver archivedDataWithRootObject:paramData];`
输出
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":"(
{
parameterName = anandShankar;
parameterOrdering = 1;
parameterSorting = 1;
parameterType = Text;
}
)","catalogMode":"xxxxxx"}}
期望输出:
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":[{
"parameterName" : "anandShankar",
"parameterOrdering" : 1,
"parameterSorting" : 1,
"parameterType" : "Text"
}],"catalogMode":"xxxxxx"}}
答案 0 :(得分:1)
它没有错。在控制台或日志圆括号()
表示数组。如果它显示圆括号那么它是数组。你永远不会在控制台或日志中使用[]
方括号。
更新:
NSData *data = [NSJSONSerialization dataWithJSONObject:paramData options:kNilOptions error:nil];
然后将此数据发送到服务器。它将在你想要的json fromat
希望这会有所帮助:)
答案 1 :(得分:0)
试试这段代码:
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
@"Object1",@"parameterName",
@"Object2", @"parameterType",
@'Object3',@"parameterSorting",@"Object4",
@"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = @{@"rqBody":@{@"catalogName":@"",@"userId":@"", @"parameter":paramArray, @"catalogMode":@""}};
添加以下行:
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:paramData options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", myString); // it will print valid json
<强> JSON 强>
{
"rqBody":{
"catalogName":"",
"parameter":[
{
"parameterOrdering":"Object4",
"parameterName":"Object1",
"parameterType":"Object2",
"parameterSorting":51
}
],
"userId":"",
"catalogMode":""
}
}