当我创建一个数组并转换为json字符串时,Json字符串无效

时间:2014-06-10 16:32:58

标签: ios objective-c json nsmutablearray nsmutabledictionary

我创建了几个词典并将它们添加到NSMutableArray中,如下所示:

NSMutableDictionary *myDictionary=[[NSMutableDictionary alloc]init];
[myDictionary setObject:@"test_name" forKey:@"option_name"];
[myDictionary setObject:@"15" forKey:@"option_id"];

NSMutableDictionary *myDictionary2=[[NSMutableDictionary alloc]init];
[myDictionary2 setObject:@"test_name2" forKey:@"option_name"];
[myDictionary2 setObject:@"16" forKey:@"option_id"];

NSMutableArray *myArray=[[NSMutableArray alloc]init];
[myArray addObject:myDictionary];
[myArray addObject:myDictionary2];

当我打印myArray时,我明白了:

(
  {
     "option_id" = 15;
     "option_name" = "test_name";
  },
  {
    "option_id" = 16;
    "option_name" = "test_name2";
  }
)

当我尝试使用此数组创建JSON字符串时,它无效。 JSON字符串是这样的:

 {"function":"myFunction", "parameters": {"result":[{"question_name":"my question","question_id": "15", "options_array":[

    {
     "option_id" = 15;
     "option_name" = "test_name";
    },
    {
    "option_id" = 16;
    "option_name" = "test_name2";
   }]}


   ]}
 }

我在哪里弄错了?请帮我解决一下。

1 个答案:

答案 0 :(得分:0)

您必须以某种奇怪的方式将NSMutableArray转换为JSON字符串。这对我很有用:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:kNilOptions error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"myArray JSON string: %@", jsonString);
// log: myArray JSON string: [{"option_id":"15","option_name":"test_name"},{"option_id":"16","option_name":"test_name2"}]