0

我想生成以下格式的 JSON 字符串:

{
    "test": {
        "currency": "USD",
        "gte": "100"
    }
}

当我执行以下代码行时:

                NSMutableArray *tempArray = [[NSMutableArray alloc] init];
                [tempArray addObject:tempDict];
                [tempArray addObject:subDict];

                [dict setObject:tempArray forKey:@"test"];

我检索了这个 JSON 字符串。

{
    "test": [{
        "currency": "USD"
    }, {
        "gte": "100"
    }]
}

知道我哪里出错了吗?

4

4 回答 4

0

从您当前的尝试中,您正在将字典数组添加到字典中,因此它的显示如下

{"test":[{"currency":"USD"},{"gte":"100"}]}

您需要添加字典,尝试关注,

 NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:
                            tempDict,
                            subDict,
                            nil];
    NSDictionary *final=@{@"test": dict};
于 2013-10-29T06:56:41.077 回答
0

这个怎么样?

NSMutableDictionary *dic = [@{} mutableCopy];
NSMutableDictionary *tempDic = [@{} mutableCopy];
tempDic[@"currency"] = @"USD";
tempDic[@"gte"] = @"100";
[dic setObject:dic forKey:@"test"];

现代 Objective-C 风格..

于 2013-10-29T07:00:27.087 回答
0

你必须这样做:

NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];

[tempDict setObject: @"USD" forKey: @"Currency"];
[tempDict setObject: @"100" forKey: @"gte"];

[dict setObject:tempDict forKey:@"test"];
于 2013-10-29T06:53:42.800 回答
0

试试这样: -

NSDictionary *yourDict = @{@"test": @{@"currency": @"USD",@"gte": @"100"}};
于 2013-10-29T07:02:09.373 回答