我想在Objective c

时间:2018-01-02 12:25:45

标签: objective-c arrays json

我想在目标c中将nsmutable数组转换为json数组,但我也得到了一些额外的字符

我的代码

if (isSucceeded) {

NSMutableDictionary *dictFieldValue = [NSMutableDictionary dictionary];
NSMutableArray *fieldSelectedOptions = [[NSMutableArray alloc]init];
                   [fieldSelectedOptions addObject:str];


[dictFieldValue setObject:@(fieldData.fieldId) forKey:@"field_id"];
                   NSError *error;

                   NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:fieldSelectedOptions options:0 error:&error];
                 NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
  [dictFieldValue setObject:jsonString forKey:@"f_value"];

                [arrFieldValues addObject:dictFieldValue];
                   NSLog(@"arrFieldValues:%@",arrFieldValues);

               } 

输出

    arrFieldValues:(
    {
    "field_id" = 128;
    "field_value" = 5;
},
   {
    "f_value" = "[\"1\"]";
    "field_id" = 129;
}
)

但我希望输出像

arrFieldValues:(
    {
    "field_id" = 128;
    "field_value" = 5;
},
    {
    "f_value" = ["2"];
    "field_id" = 129;
}
)

我已将msmutable数组转换为json数组,然后转换为NSstring并将该字符串添加到另一个目标数组中。请告诉我这里的错误。

1 个答案:

答案 0 :(得分:1)

删除NSJSONWritingPrettyPrinted和所有字符串操作代码。

替换

NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:fieldSelectedOptions options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
jsonString =[jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"[,\\.\']" options:0 error:NULL];

jsonString = [expression stringByReplacingMatchesInString:jsonString options:0 range:NSMakeRange(0, jsonString.length)
                                                                         withTemplate:@""];
jsonString =[jsonString stringByReplacingOccurrencesOfString:@" " withString:@""];
[dictFieldValue setObject:jsonString forKey:@"f_value"];

NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:fieldSelectedOptions options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
dictFieldValue[@"f_value"] = jsonString;

我想知道为什么几乎所有的教程都提出了漂亮的打印选项。

服务器根本不关心美学。