将对象作为singleArrayObject,如何在NSMutableArray中进行转换?

时间:2018-03-12 14:17:47

标签: objective-c json nsmutablearray nsarray

作为回应,我得到gas_cylinders密钥作为单个数组对象

"gas_cylinders":["[{\"quantity\":\"2\",\"name\":\"Medium Blue\",\"price\":\"100.0\",\"total_price\":\"200.0\"},{\"quantity\":\"3\",\"name\":\"Green\",\"price\":\"100.0\",\"total_price\":\"300.0\"},{\"quantity\":\"1\",\"name\":\"Dark Green\",\"price\":\"100.0\",\"total_price\":\"100.0\"}]"]

注意: - tripDictionary包含以下数据..

(lldb) po tripDictionary 
{
    "gas_cylinder_total" = 600;
    "gas_cylinders" =     (
        "[{\"quantity\":\"2\",\"name\":\"Medium Blue\",\"price\":\"100.0\",\"total_price\":\"200.0\"},{\"quantity\":\"3\",\"name\":\"Green\",\"price\":\"100.0\",\"total_price\":\"300.0\"},{\"quantity\":\"1\",\"name\":\"Dark Green\",\"price\":\"100.0\",\"total_price\":\"100.0\"}]"
    );
}

我正在采取以下方式gas_cylinders ..

NSArray *arr = [tripDictionary valueForKey:@"gas_cylinders"];
if (arr && arr.count > 0) {
   NSLog(@"first obj = %@",arr[0]);
}

以上NSLog的输出,如..

first obj = [{"quantity":"2","name":"Medium Blue","price":"100.0","total_price":"200.0"},{"quantity":"3","name":"Green","price":"100.0","total_price":"300.0"},{"quantity":"1","name":"Dark Green","price":"100.0","total_price":"100.0"}]

如何在NSMutableArray中获取此对象?

1 个答案:

答案 0 :(得分:2)

数据不是您认为的。 gas_cylinders键的值是一个JSON字符串数组。

NSArray *cylinders = tripDictionary[@"gas_cylinders"];
NSString *firstCylinder = cylinders[0];

此时,firstCylinder是一个JSON字符串。您需要解析该JSON字符串以获取JSON字符串中包含的所需字典数组。