I want to store a message - "hi this is John KL", in some string, how to parse following example.
[
{
"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. 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. [String : Any]
is most commonly used dictionary but according to your data it suites with [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.
if let dictionary = array.first as? [String : Any] {
if let stringMessage = dictionary["message"] as? String {
print("stringMessage - \(stringMessage)")
}
}
Objective-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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.