gpt4 book ai didi

ios - 具有多个字段的 JSON 字符串

转载 作者:行者123 更新时间:2023-11-29 12:10:37 24 4
gpt4 key购买 nike

我目前正在使用以下方法从 iOS 应用程序向服务器发送一些简单的 json:

NSData *jsonData = [@"{ \"item\": \"hat\" }" dataUsingEncoding:NSUTF8StringEncoding];

我想添加一堆其他字段和值。

包含更多字段的适当语法是什么?

有点像

 NSData *jsonData = [@"{ \"item\": \"hat\",\"id\":2,\"color\":\"blue\" }" dataUsingEncoding:NSUTF8StringEncoding];

或者有没有更好的方法,比如发送字典?

最佳答案

创建字典:

NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:'Value' forKey:'Key']; //adding values

您可以使用 JSONKit

像这样将 NSDictionary 转换为 Json 字符串:

NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil];

或者您可以使用 SBJson

NSString *jsonString = [dictionary JSONRepresentation];

而且你可以在没有第三方框架的情况下做到这一点:

NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];

if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

关于ios - 具有多个字段的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33529604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com