我正在尝试以角度构建Azure认知文本翻译器应用程序。最初,我需要加载支持的语言。但是,当我使用此链接https://api.cognitive.microsofttranslator.com/languages?api-version=3.0
时。我正在收到这样的回复
"translation": {
"af": {
"name": "Afrikaans",
"nativeName": "Afrikaans",
"dir": "ltr"
},
"ar": {
"name": "Arabic",
"nativeName": "العربية",
"dir": "rtl"
},
"bg": {
"name": "Bulgarian",
"nativeName": "Български",
"dir": "ltr"
},
...
}
如何创建一个包含此类json的模型?
当我尝试使用json2ts.com建立模型时,它会为每种语言创建对象,例如
export interface Af {
name: string;
nativeName: string;
dir: string;
}
export interface Ar {
name: string;
nativeName: string;
dir: string;
}
export interface Bg {
name: string;
nativeName: string;
dir: string;
}
export interface Translation {
af: Af;
ar: Ar;
bg: Bg;
}
我需要为所有可用语言创建界面吗? 还有其他简单的方法可以解决这个问题吗?
答案 0 :(得分:0)
您可以定义一个对JSON数据建模的Typescript接口。
export interface LanguageInfo {
name: string
nativeName: string
dir: string
code?: string
toScripts?: Array<LanguageInfo>
}
export interface TranslationLanguages {
langCode: string
info: LanguageInfo
}
function fromJSON(json_data: string | Object): TranslationLanguages {
let obj: TranslationLanguages;
if (typeof json_data === "object") {
obj = json_data as TranslationLanguages;
} else {
obj = JSON.parse(json_data);
}
return obj;
}
答案 1 :(得分:0)
该对象的translation
属性是键值映射。
您可以按如下所示对整个事物进行建模:
type Dir = "ltr" | "rtl";
interface Translation {
name:string;
nativeName:string;
dir: Dir;
}
interface LangResponse {
translation: {[langCode:string]: Translation};
}