将 NSString 转换为正确的 JSON 格式

Converting NSString to proper JSON format

正在将 NSString 转换为正确的 JSON 格式..

NSString *input_json = [NSString stringWithFormat:@"{\"id\":\"%@\",\"seconds\":\"%d\",\"buttons\": \"%@\"}", reco_id, interactionTime, json_Buttons];

这里json_Button是从nsdictionary..

转换过来的json格式

我的 input_json 结果是:

{"id":"119","seconds":"10","buttons": "{
  "update" : "2",
  "scan" : "4"
}"}

它的格式不正确 JSON。按键按钮包含“{}”我想删除这些引号。

预期结果是:

{
    "id": "119",
    "seconds": "10",
    "buttons": {
        "update": "2",
        "scan": "4"
    }
}

你完全错了。首先,创建一个 NSDictionary,其中包含您要转换为 JSON 的所有数据。然后使用 NSJSONSerialization 将字典正确转换为 JSON.

像这样的东西会起作用:

NSDictionary *dictionary = @{ @"id" : reco_id, @"seconds" : @(interactionTime), @"buttons" : json_Buttons };
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if (data) {
    NSString *jsonString = [[NSString alloc] intWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"JSON: %@", jsonString);
} else {
    NSLog(@"Unable to convert dictionary to JSON: %@", error);
}

尝试手动构建 JSON 字符串是个坏主意。使用 NSJSON 序列化 class。这很容易。创建字典,然后调用 dataWithJSONObject:options:error:

如果您使用选项:NSJSONWritingPrettyPrinted,它会插入换行符和空格,使 JSON 更具可读性。

通过使用该函数,您每次都能得到正确的格式 JSON,而且它很灵活,因为如果您向它发送不同的词典,您会得到不同的 JSON。