gpt4 book ai didi

ios - 从 json 中获取单个特定值

转载 作者:行者123 更新时间:2023-11-29 02:57:48 24 4
gpt4 key购买 nike

正如您所料,我对 obj-C 相当陌生,并且我一直在努力积累知识和经验。但我仍然在努力解决很多概念,其中包括 JSON 数据“捕获”。我看过很多教程和指南,但我无法将它们翻译成我需要的内容。大多数时候,他们将数据布置在数组中或获取多个值,并且(当然)使用不同的变量,这让我感到困惑和不清楚,尽管这应该非常简单。

我正在尝试做一些非常简单的事情:从开放天气 API 获取单个值,即温度。

我会告诉你我的代码,根据我可耻的知识,它应该是完美的,但显然它不起作用:D

@implementation HomeViewController
{

NSMutableArray *tableData;
NSDictionary *jsonDict;
NSMutableString *title;
}
-(void) viewDidLoad
{
[super viewDidLoad];

NSError *error;


//I create my data array and the string i'll store my value later on
tableData = [[NSMutableArray alloc] init];
title = [[NSMutableString alloc]init];

// Creating the link for the json api so it fits coordinates ; this works but i edited the locations out to clear the code
NSString *s = [[NSString alloc]initWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%.05f&lon=%.05f", _annotation.coordinate.latitude, _annotation.coordinate.longitude];

// I go online and catch the data of the url stored in S
NSData *jSonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:s]];

// This is a dictionary where all my data is stored from jsonData, keys and values all the way
jsonDict = [NSJSONSerialization JSONObjectWithData:jSonData options:NSJSONReadingMutableContainers error:&error];

// I use the string created previously and assign it the value stored in that dictionary, in the TEMP 'folder', right under MAIN.

title = [[jsonDict objectForKey:@"main"]objectForKey:@"main.temp"];

// I assign that title to a label so it appears in my view.
self.tempLabel.text = title;
...
}

给你。我可能错过了一些非常简单的东西,但我一直坚持这一点,即使我觉得我知道我在做什么,我可能错过了一些东西。所以如果你给我的答案,你也可以告诉我我做错了什么,那就太好了:D

非常感谢您的支持和知识。这个社区很棒 :)

最佳答案

jsonDict赋值后打断点,使用

po jsonDict

在控制台打印出你得到的东西。然后,调整提取值的代码。并为其使用现代 Objective-C 语法。

例子

title = jsonDict[@"main"][@"temp"];

注意事项

po 是一个调试器命令,它将打印出对象的内容。如果您需要打印出原语的内容,请改用 p

关于ios - 从 json 中获取单个特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23688638/

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