gpt4 book ai didi

ios - 解析 JSON 对象和子元素

转载 作者:行者123 更新时间:2023-11-29 01:50:03 24 4
gpt4 key购买 nike

我只需要知道解析 JSON 字符串的正确方法。这是我的示例 JSON 响应:

[
{
"my_response": [
{
"name": "XXX",
"Area": "XXX",
"Num": 123
}
]
},
{
"other_response": [
{
"message": "Hello",
"status": "Success",
"flag_value": "1"
}
]
}
]

我想解析 String 中的 flag_value

这个方法我试过了

NSString *str1 = [json valueForKeyPath:@"other_response. flag_value"];
NSLog(@"str %@",str1);

我的输出是这样的

str (
"<null>",
(
1
)
)

但我希望我的输出是这样的字符串:

1

最佳答案

[{"my_response":[{"name":"XXX","Area":"XXX","Num":123}]},{"other_response":[{"message":"Hello","status":"Success","flag_value":"1"}]}]

实际上你的 Json 响应Array 开始所以按照这个步骤

第一步

NSArray *jsonDict = [NSJSONSerialization JSONObjectWithData:yourData options:Kniloptions error:nil];

第二步

在这里你有2本字典

NSString *FlagStr;
for (NSMutableDictionary *temp in jsonDict)
{

NSArray *secondOption=[temp objectForKey:@"other_response"];

for (NSMutableDictionary *second in secondOption)
{
FlagStr=[second objectForKey:@"flag_value"];
}

}

选择 2

我不会尝试这个,但可能对你有用,一旦检查

第一步

NSArray *jsonDict = [[[NSJSONSerialization JSONObjectWithData:yourData options:Kniloptions error:nil]objectAtIndex:1] objectForKey:@"other_response"];

第二步

 NSString *FlagStr;

for (NSMutableDictionary *second in secondOption)
{
FlagStr=[temp objectForKey:@"flag_value"];
}

选择 3

您可以直接获取字符串值我没有尝试过,但可能对您有用,一旦检查过

 NSString *flage = [[[NSJSONSerialization JSONObjectWithData:yourData options:Kniloptions error:nil]objectAtIndex:1] objectForKey:@"other_response"]objectAtIndex:0] objectForKey:@"flag_value"];

关于ios - 解析 JSON 对象和子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31511507/

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