以下是一些代码:
- (IBAction)buttonClicked:(id)sender
{
self.alertController = [UIAlertController alertControllerWithTitle: nil
message: nil
preferredStyle: UIAlertControllerStyleAlert];
MyCustomViewController *v = [[MyCustomViewController alloc] init];
[self.alertController setValue:v forKey:@"contentViewController"];
[self presentViewController: self.alertController animated: true completion: nil];
}
它读入此文件:
import fs = require('fs');
export interface Answer {
order: number,
text: string
}
export class Config {
responses:Answer[];
timestamp_column: string;
name_column: string
fromJSONFile(fileName: string) {
var fileString = fs.readFileSync(fileName);
var parsedFile = JSON.parse(fileString.toString());
this.responses = parsedFile.responses;
this.timestamp_column = parsedFile.timestamp_column;
this.name_column = parsedFile.name_column;
}
mapAnswerToNum(answer:string):number {
for (var a of this.responses) {
if (a.text == answer) { return a.order;}
}
throw new Error(`Invalid response string ${answer}`);
}
}
请注意,我正在从fromJSONFile中逐个复制每个实例变量的相应JSON字段。似乎重复,因为我注意确保类的结构与JSON文件完全相同。还有更好的方法吗?
答案 0 :(得分:1)
使用Object.assign
fromJSONFile(fileName: string) {
var fileString = fs.readFileSync(fileName);
var parsedFile = JSON.parse(fileString.toString());
Object.assign(this,parsedFile);
}