gpt4 book ai didi

ios - 如何将打印的字典转换为 NSDictionary?

转载 作者:行者123 更新时间:2023-12-01 20:11:58 27 4
gpt4 key购买 nike

当我 NSLog 字典输出是这样的:

{
accounts = (
{
"account_number" = 9000012;
"account_type" = "Saver Account";
ato = 0;
balance = "0.0";
},
{
"account_number" = 9000010;
"account_type" = "Primary Account";
ato = 0;
balance = "100000.0";
}
);
}

现在我需要在另一个程序中使用相同的字典(在我的测试中模拟)。
如何将此值从控制台复制粘贴分配到 NSDictionary?

我试图将其设置为 NSString 作为这个答案解释
NSString *jsonStr = @" { ({\"account_number\" = 9000012; \"account_type\" = \"Saver Account\"; ato = 0; balance = \"0.0\";});}";
NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
return dict;

Converting NSString to NSDictionary / JSON

但这是返回空值。

我再次将 = 替换为 : 并尝试了
NSString *jsonStr = @" { ({\"account_number\" : 9000012; \"account_type\" : \"Saver Account\"; ato : 0; balance : \"0.0\";});}";

但还是不行?

更新

我设法以这种方式转换:
NSDictionary *account = @{ @"account_type":@"Account Type XXX",
@"account_number":@"Account Number 123" };

NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] init];
[mainDict setValue:@[account] forKey:@"accounts"];

对于两个数组:
NSDictionary *account1 = @{ @"account_type":@"Account Type XXX",
@"account_number":@"Account Number 123" };

NSDictionary *account2 = @{ @"account_type":@"Account Type YYY",
@"account_number":@"Account Number 456" };


NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] init];
[mainDict setValue:@[account1,account2] forKey:@"accounts"];

但是@Duncan C 声称这种方式不安全!

最佳答案

不要那样做。 NSLog 的输出没有任何特定的格式,并且不能保证在操作系统版本之间保持一致。您将不得不编写一堆自定义代码,它会很脆弱,并且会因任何操作系统更改而中断。
您应该编写一个函数来获取您的字典并将其输出为漂亮的 JSON。还要编写另一个函数,将 JSON 作为输入并返回一个字典。然后从调试器调用这些函数。
编辑:
我创建了一个定义 NSDictionary 类别 NSDictionary+JSON 的 Github 项目
DictionaryToJSON project on Github
如果添加 NSDictionary+JSON.hNSDictionary+JSON.m到您的项目和#import使用它的任何文件中的 header ,您可以在调试器中键入这样的行:

e [someDictionary jsonString]
这将需要 someDictionary 并将其转换为 JSON 字符串。它还会转义字符串中的任何引号,以便您可以复制/粘贴它,然后您可以转到其他程序(也包含类别)并键入
e dict = [NSDictionary dictionaryFromJSONString: @"<the JSON string>"]
(将 "<the JSON string>" 替换为从上一个调试器命令中获得的实际 JSON 字符串。
请注意,为了能够将 JSON 从调试器控制台复制/粘贴到调试器命令中,我必须将 JSON 数据中的任何引号转义为 \" .

关于ios - 如何将打印的字典转换为 NSDictionary?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37589782/

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