[英]How to get a value from dictionary which is inside an array?
I want to store a message - "hi this is John KL", in some string, how to parse following example. 我想存储一条消息-“嗨,这是John KL”,以字符串形式显示如何解析以下示例。
[
{
"message": "hi this is John KL"
}
]
guard let anArray = input as? [[String:String]],
let message = anArray.first["message"] else {
print("unable to fetch data"
}
- (void) readJSON {
NSError *result;
NSURL *url = [[NSBundle mainBundle] URLForResource: @"sample"
withExtension: @"JSON"];
NSData *data = [NSData dataWithContentsOfURL: url
options: 0
error: &result];
if (result != nil) {
NSLog(@"Error reading file: %@", result);
return;
}
NSArray<NSDictionary<NSString*, NSString*> *> *array = [NSJSONSerialization JSONObjectWithData: data options: 0 error: &result];
if (result != nil) {
NSLog(@"Error converting JSON: %@", result);
return;
}
else {
NSLog(@"\nJSON data = \n%@", array);
if (array.count < 1) {
NSLog(@"Not enough elements in array");
return;
}
NSString *message = array[0][@"message"];
if (message == nil) {
NSLog(@"Unable to fetch message");
} else {
NSLog(@"Message = \"%@\"", message);
}
}
}
The above Objective-C code does not test to make sure the object read from the JSON file is the correct type. 上面的Objective-C代码无法测试以确保从JSON文件读取的对象是正确的类型。 It will crash if it is not an array containing a dictionary with a string key and string value. 如果它不是包含带有字符串键和字符串值的字典的数组,它将崩溃。 For a production app you'll want to add code to type-check the data. 对于生产应用程序,您需要添加代码以对数据进行类型检查。
Swift 迅速
Assign your json array to a variable type of [String : String]
or [String : Any]
dictionary array. 将您的json数组分配给[String : String]
或[String : Any]
字典数组的变量类型。 [String : Any]
is most commonly used dictionary but according to your data it suites with [String : String]
[String : Any]
是最常用的字典,但根据您的数据,它适合[String : String]
if let array = [
{
“message” : “hi this is John KL”
}
] as [Any]
Now, get your json/dictionary from array using index value and then get string from json using json key. 现在,使用索引值从数组获取json / dictionary,然后使用json键从json获取字符串。
if let dictionary = array.first as? [String : Any] {
if let stringMessage = dictionary["message"] as? String {
print("stringMessage - \(stringMessage)")
}
}
Objective-C 目标C
NSArray * array = [
{
“message” : “hi this is John KL”
}
];
NSDictionary * dictionary = (NSDictionary *)[array objectAtIndex: 0];
NSString * stringMessage = (NSString *)[dictionary valueForKey: "message"];
NSLog(@"stringMessage - %@",stringMessage);
You can try this answer. 您可以尝试此答案。
NSArray *result = [json objectForKey:@"result"];
for(NSString *currenObject in result){
NSLog(@"%@",currenObject);
NSString *currentValue = [currenObject valueForKey:@"message"];
}
NSLog(@"%@",currentValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.